r-根据一个条件在数据帧中预先设置变量的前缀,然后创建一个新的变量来显示哪些变量被加了前缀



我有一个包含变量RingNo的数据帧

> head(df)
Place Book.Number  RingNo
1   WYT     2020#01  603701
2   WYT     2020#01  603701
3   WYT     2020#01  603701
4   WYT     2020#01  603702
5   WYT     2020#01  603703
6   WYT     2020#01  AFH5490

我想在CCD_ 2中的任何字符串前面加一个";x〃;如果它们只有6个字符。df$RingNo中的所有字符串都有6个或7个字符。

我可以通过实现上述目标

inds <- nchar(df$RingNo) == 6
df$RingNo[inds] <- paste0('x', df$RingNo[inds])
> head(df)
Place Book.Number  RingNo
1   WYT     2020#01 x603701
2   WYT     2020#01 x603701
3   WYT     2020#01 x603701
4   WYT     2020#01 x603702
5   WYT     2020#01 x603703
6   WYT     2020#01 AFH5490

然而,如果我现在可以创建一个新的变量df$Comment,它指示哪些变量被加了前缀,那也会非常有用。这是一个超过200000行的巨大数据帧。所以我得到了类似的东西

Place Book.Number RingNo Comment
1   WYT     2020#01 x603701 Prefixed with an x
2   WYT     2020#01 x603701 Prefixed with an x
3   WYT     2020#01 x603701 Prefixed with an x
4   WYT     2020#01 x603702 Prefixed with an x
5   WYT     2020#01 x603703 Prefixed with an x
6   WYT     2020#01 AFH5490

您可以再次使用相同的inds变量:

df$Comment <- ''
df$Comment[inds] <- 'Prefixed with an x'

我们可以用ifelse做到这一点

df$Comment <- ifelse(inds, 'Prefixed with an x', '')

最新更新