我有一个数据帧df
,它有一个chr列Col1
,看起来像这样:
<表类>
Col1
tbody><<tr>"苹果;橙色;pear" "橙色apple" 表类>
一种基数R方法来计算以";"分隔的单词数是:
lengths(gregexpr(";", df$Col1)) + 1
# [1] 3 2
创建一个新列,只需:
df$NewCol <- lengths(gregexpr(";", df$Col1)) + 1
# Col1 NewCol
# 1 apple;orange;pear 3
# 2 orange;apple 2
数据df <- data.frame(Col1 = c("apple;orange;pear","orange;apple"))