R for循环:使用不同列中的子字符串的计数创建一个新列 [英] R for loop: create a new column with the count of a sub str from a different column

查看:182
本文介绍了R for循环:使用不同列中的子字符串的计数创建一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经捣鼓R,现在似乎都逃脱了我。 。 。

我有一个有数百列和大约100k行的表格。其中一列包含有时有逗号的字符串(例如鸡,山羊,牛或只是鸡)。我需要一个(我相信)for循环的脚本,可以创建一个新的列(我知道新的列代码不应该在for循环),计算逗号的数量(或问题列中的条目数少一个),并添加一个,所以我可以找出有多少条目在每一列。例如:

  col 

鸡,山羊
牛,鸡,山羊
cow

我想让脚本在表格中创建一个额外的列, 。 。

  col2 
1
2
3
1


解决方案

使用 stringr 包...

  require(stringr)
dat $ aninum< - sapply(dat $ ani,str_count,pattern =',')+ 1



  ani aninum 
1鸡1
2鸡,山羊2
3牛,鸡,山羊3
4牛1


I used to fiddle with R and now it all seems to have escaped me . . .

I have a table with a few hundred columns and about 100k rows. One of those columns contains strings that sometimes have commas in them (e.g. chicken,goat,cow or just chicken). I need a script with a (I believe) for loop that can create a new column (I know the new column code should not be in the for loop), count the number of commas (or the number of entries in the column in question less one) and add one so I can find out how many entries are in each column. An example:

col
chicken
chicken,goat
cow,chicken,goat
cow

I want a script to turn create an additional column in the table that would look like . . .

col2
1
2
3
1

解决方案

A loop is not needed here, I think. Using the stringr package...

require(stringr)
dat$aninum <- sapply(dat$ani,str_count,pattern=',')+1

which gives

               ani aninum
1          chicken      1
2     chicken,goat      2
3 cow,chicken,goat      3
4              cow      1

这篇关于R for循环:使用不同列中的子字符串的计数创建一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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