Skip to content
Prev 359882 / 398502 Next

simple question on data frames assignment

Lapply is not a vectorized function. It is compact to read, but it would not be worth using for this calculation. 

However, if your data frame had multiple color columns in your data frame that you wanted to make responses for then you might want to use lapply as a more compact version of a for loop to repeat this operation. 

colordata2 <- data.frame(id = c(1,2,3,4,5), color1 = c("blue", "red",
"green", "blue", "orange"), color2 = c("orange", "green",
"blue", "red", "red"))
responses <- lapply( colordata2[ -1 ], function(col) { ifelse(col == 'blue', 1, 0) } )
names(responses) <- names( colordata2 )[-1]

where each of the columns other than the first is handed in turn to the anonymous function that does the response calculation. The result is a data frame (list of columns) with no column names, so I give the new columns names based on the old column names. You could choose different names,  e.g.

names(responses) <- paste0( "response", 1:2 )

but you have to be careful to fix that code whenever you change the colordata2 data frame to have more columns.