R根据另一列中的字符匹配增加列值

时间:2014-11-24 17:12:52

标签: r dataframe

我有一组数据可以大致建模如下:

x=data.frame(c(2,2,2),c(3,4,6),c(3,4,6), c("x/-","x/x","-/x"))
names(x)=c("A","B","C","D")

如果 D中的第一个字符是 - ,我希望将B的值更改为(C + 1)。

我尝试过使用以下内容并迭代行:

if(substring(x$D, 1,1) == "-") 
{
  x$B <- x$C + 1       
}

然而,这种方法似乎不起作用。有没有办法用sapply来做到这一点?

谢谢,

马特

2 个答案:

答案 0 :(得分:2)

您可以使用ifelsewithin

within(x, B <- ifelse(substr(D, 1, 1) == "-", C + 1, B))
#   A B C   D
# 1 2 3 3 x/-
# 2 2 4 4 x/x
# 3 2 7 6 -/x

或者代替substr,您可以使用grepl

within(x, B <- ifelse(grepl("^[-]", D), C + 1, B))
#   A B C   D
# 1 2 3 3 x/-
# 2 2 4 4 x/x
# 3 2 7 6 -/x

答案 1 :(得分:1)

data.table解决方案。

require(data.table)

x <- data.table(c(2,2,2), c(3,4,6), c(3,4,6), c("x/-","x/x","-/x"))
setnames(x, c("A","B","C","D"))

x[grepl("^[-]", D), B := C + 1]
相关问题