R – Loop through columns and add string lengths as new columns

loopsr

I have a data frame with a number of columns, and would like to output a separate column for each with the length of each row in it.

I am trying to iterate through the column names, and for each column output a corresponding column with '_length' attached.

For example col1 | col2 would go to col1 | col2 | col1_length | col2_length

The code I am using is:

df <- data.frame(col1 = c("abc","abcd","a","abcdefg"),col2 = c("adf qqwe","d","e","f"))

for(i in names(df)){
  df$paste(i,'length',sep="_") <- str_length(df$i)
 }

However this throws and error:

invalid function in complex assignment.

Am I able to use loops in this way in R?

Best Answer

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}
Related Topic