简体   繁体   中英

Transform R dataframes using variables in loop

I am trying to replace values in a R dataframe by column. I would like to loop though a given list of columns of the dataframe and replace all "Yes" values by 1 and all the other values by 0.

I tried to do this using transform() and ifelse() functions with the something like this:

# List of selected Columns:
ColumnNames = c("Frigori", "Microond" , "Arca", "Aspira")

# Replace Values in dataframe
for(i in 1:length(ColumnNames)){
dataframe <- transform(dataframe, ColumnNames[i] = ifelse(Columnames[i] == "Yes", 1, 0))
}

This piece of code works fine with explicit column names outside the loop, but with the array it will give me the following error:

Error: unexpected '=' in:
"for(i in 1:length(Appliances)){
dataframe <- transform(dataframe, ColumnNames[i] ="

I don't know what goes wrong here, but the problem has to be related with the variable substitution.

The code can actually be simplified to one short line with no loops or apply() at all:

dataframe <- data.frame(a = c("No", "Yes", "No", "No", "Yes"),
                        b = c("Hi", "Hi", "Mom", "Hi", "Mom"),
                        c = c("Yes", "Yes", "Yes", "Yes", "No"))
cols <- c("a","c")
dataframe[,cols] <- as.numeric(dataframe[,cols]=="Yes")
dataframe

  a   b c
1 0  Hi 1
2 1  Hi 1
3 0 Mom 1
4 0  Hi 1
5 1 Mom 0

Simulated data:

data <- data.frame(matrix(ifelse(runif(40)>.5,"YES",letters[1:26]), 10, 4))

Suppose you want to change columns X2 and X4

cols <- c("X2","X4")
data[,cols] <- apply(data[cols],2,function(x) ifelse(x=="YES",1,0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM