遍历列并将字符串长度添加为新列 [英] Loop through columns and add string lengths as new columns

查看:75
本文介绍了遍历列并将字符串长度添加为新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我正在尝试遍历列名,并为每个列输出一个附加了'_length'的对应列.

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

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

For example col1 | col2 would go to 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)
 }

但是这会引发错误:

复杂分配中的无效函数.

invalid function in complex assignment.

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

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

推荐答案

您需要使用[[,它与$等效.否则,例如,当icol1时,R将查找df$i而不是df$col1.

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]])
}

这篇关于遍历列并将字符串长度添加为新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆