Create a for to consult values of a data

2

I have a data with several variables and I want to use a for to scroll through several variables and check the values.

The data table data contains the variables V1, V2 ... V15. What I want is to create a Stotal variable that is the sum of the SI values that exist in the variables V1 to V15.

for (i in 1:nrow(datos)){
for (j in 1:15){
   (if(sprintf("V%d",j)[i])=="SI"){
aux<-1
Stotal[i]<-1+aux
}
}

The code does not work, among other things, because the sprintf function pastes the text but does not take the value of the variable in the position that I ask.

Edited: An example with fewer columns could be:

V1 <- c("Si","No","Si")
V2 <- c("Si","No","No")
V3<-c("Si","Si","Si")

datos <- data.frame(V1,V2,V3)
datos
  V1 V2 V3
1 Si Si Si
2 No No Si
3 Si No Si

In this case the expected output would be: 3 1 2

    
asked by Uko 07.12.2017 в 13:15
source

2 answers

0

You can use a dataframe:

Sval<-0   
# Creo tres vectores of misma tamano. Utiliso tres vectores para simplicidad
V1 <- c(5,9,3)
V2 <- c(10,11,12)
V3<-c(13,14,15)
X <- data.frame(V1,V2,V3)    
rownames(X) <- c("SI","b","c")
datos <- X    
print(datos)

What it gives:

   V1 V2 V3
SI  5 10 13
b   9 11 14
c   3 12 15

And to calculate the IF attribute values:

for (val in datos["SI",]){
    Stotal=Stotal + val
}

print(Stotal)

That gives

  

[1] 28

    
answered by 07.12.2017 в 16:30
0

Beyond what you can solve with a loop R has more effective and performant mechanisms. For example:

V1 <- c("Si","No","Si")
V2 <- c("Si","No","No")
V3<-c("Si","Si","Si")

datos <- data.frame(V1,V2,V3)
datos
apply(datos, MARGIN = 1, function(x) sum(ifelse(x=="Si", 1, 0)))

The Exit:

  V1 V2 V3
1 Si Si Si
2 No No Si
3 Si No Si

V1 V2 V3 
 2  1  3 
  • We apply apply() the sum to datos per row MARGIN = 1
  • But we only add 1 if the value is Si ( ifelse(x=="Si", 1, 0) )

Or even much easier:

rowSums(datos[,]=="Si")
  • We apply rowSums to add per row, only values that are Si ( datos[,]=="Si" )
answered by 07.12.2017 в 17:39