循环遍历列并将字符串长度添加为新列

Zfu*_*unk 30 loops r

我有一个包含多个列的数据框,并希望为每个列输出一个单独的列,其中包含每行的长度.

我试图遍历列名称,并为每个列输出附加'_length'的相应列.

例如col1 | col2将转到col1 | col2 | col1_length | col2_length

我使用的代码是:

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)
 }
Run Code Online (Sandbox Code Playgroud)

然而这引发了错误:

复杂赋值中的函数无效.

我能在R中以这种方式使用循环吗?

flo*_*del 69

你需要使用[[,程序化的等价物$.否则,例如,当icol1,R会寻找df$i代替df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}
Run Code Online (Sandbox Code Playgroud)


Sim*_*lon 10

你可以lapply用来传递每一列str_length,然后传递cbind给你原来的data.frame......

library(stringr)

out <- lapply( df , str_length )    
df <- cbind( df , out )

#     col1     col2 col1 col2
#1     abc adf qqwe    3    8
#2    abcd        d    4    1
#3       a        e    1    1
#4 abcdefg        f    7    1
Run Code Online (Sandbox Code Playgroud)


m0n*_*awk 6

随着dplyrstringr您可以使用mutate_all:

> df %>% mutate_all(funs(length = str_length(.)))

     col1     col2 col1_length col2_length
1     abc adf qqwe           3           8
2    abcd        d           4           1
3       a        e           1           1
4 abcdefg        f           7           1
Run Code Online (Sandbox Code Playgroud)