根据R中两列的字符串长度选择行 [英] selecting rows on basis of the string length of two columns in R

查看:197
本文介绍了根据R中两列的字符串长度选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择列v3中字符串长度等于列v4的字符串长度的数据帧的行。
我的数据框'df'看起来像:

I want to select the rows of a data frame in which the length of the string in the column v3 is equal to the length of the string of the column v4. My dataframe 'df' looks like:

    v1  v2  v3  v4
1   456 .   C   T
2   462 .   C   T
3   497 .   C   T
4   499 .   GC  AC
5   499 .   GC  G
6   499 .   GC  CC
7   513 .   GCACA   GCA
8   513 .   GCACA   GCACACA
9   513 .   GCACA   ACACA
10  513 .   GCACA   GCACACACA
11  513 .   GCACA   GCACACACACA

12  513 .   GCACA   GACCACA
13  513 .   GCACA   G
14  521 .   ACN A
15  522 .   CNN C

输出应为:

v1  v2  v3  v4
1   456 .   C   T
2   462 .   C   T
3   497 .   C   T
4   499 .   GC  AC
9   513 .   GCACA   ACACA

我尝试过:
new_df = df [nchar str_sub(df $ v3))== nchar(str_sub(df $ v4))]

推荐答案

@agstudy得到最重要的部分。我会补充说, str_sub (从 stringr 包我假设)在这里没有任何有用的东西。最后,您可以使用子集避免重复使用 df $ 。所以你可以做:

@agstudy got the most important part. I would add that str_sub (from the stringr package I assume) is not doing anything useful here. Last, you could use subset to avoid the repetitive use of df$. So you can do:

df[nchar(df$v3) == nchar(df$v4), ]

subset(df, nchar(v3) == nchar(v4))

这篇关于根据R中两列的字符串长度选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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