R - 根据应用于同一行中其他值的函数设置值
R - setting a value based on a function applied to other values in the same row
我有一个包含(惊喜)数据的数据框。我有一个列,我希望在每行的基础上填充,根据同一行中其他列的值计算。
从谷歌搜索,我似乎需要 'apply',或者它的近亲之一。不幸的是,我还没有设法让它真正发挥作用。
示例代码:
#Example function
getCode <- function (ar1, ar2, ar3){
if(ar1==1 && ar2==1 && ar3==1){
return(1)
} else if(ar1==0 && ar2==0 && ar3==0){
return(0)
}
return(2)
}
#Create data frame
a = c(1,1,0)
b = c(1,0,0)
c = c(1,1,0)
df <- data.frame(a,b,c)
#Add column for new data
df[,"x"] <- 0
#Apply function to new column
df[,"x"] <- apply(df[,"x"], 1, getCode(df[,"a"], df[,"b"], df[,"c"]))
我希望 df 取自:
a b c x
1 1 1 1 0
2 1 0 1 0
3 0 0 0 0
到
a b c x
1 1 1 1 1
2 1 0 1 2
3 0 0 0 0
不幸的是运行这吐出:
Error in match.fun(FUN) : 'getCode(df[, "a"], df[, "b"], df[,
"c"])' is not a function, character or symbol
我是 R 的新手,如果答案过于简单,我深表歉意。谢谢
一些事情:应用将沿着数据框本身(即apply(df, 1, someFunc)
);使用 $
运算符按名称访问列更为惯用。所以如果我有一个名为 df
的数据框和一个名为 a
的列,请使用 df$a
.
在这种情况下,我喜欢沿数据帧的索引执行 sapply
,然后使用该索引从数据帧中获取适当的元素。
df$x <- sapply(1:nrow(df), function(i) getCode(df$a[i], df$b[i], df$c[i]))
正如上面提到的@devmacrile,我只是修改函数,以便能够获得一个包含 3 个元素的向量作为输入,并在你提到的 apply
命令中使用它。
#Example function
getCode <- function (x){
ifelse(x[1]==1 & x[2]==1 & x[3]==1,
1,
ifelse(x[1]==0 & x[2]==0 & x[3]==0,
0,
2)) }
#Create data frame
a = c(1,1,0)
b = c(1,0,0)
c = c(1,1,0)
df <- data.frame(a,b,c)
df
# a b c
# 1 1 1 1
# 2 1 0 1
# 3 0 0 0
# create your new column of results
df$x = apply(df, 1, getCode)
df
# a b c x
# 1 1 1 1 1
# 2 1 0 1 2
# 3 0 0 0 0
我有一个包含(惊喜)数据的数据框。我有一个列,我希望在每行的基础上填充,根据同一行中其他列的值计算。
从谷歌搜索,我似乎需要 'apply',或者它的近亲之一。不幸的是,我还没有设法让它真正发挥作用。
示例代码:
#Example function
getCode <- function (ar1, ar2, ar3){
if(ar1==1 && ar2==1 && ar3==1){
return(1)
} else if(ar1==0 && ar2==0 && ar3==0){
return(0)
}
return(2)
}
#Create data frame
a = c(1,1,0)
b = c(1,0,0)
c = c(1,1,0)
df <- data.frame(a,b,c)
#Add column for new data
df[,"x"] <- 0
#Apply function to new column
df[,"x"] <- apply(df[,"x"], 1, getCode(df[,"a"], df[,"b"], df[,"c"]))
我希望 df 取自:
a b c x
1 1 1 1 0
2 1 0 1 0
3 0 0 0 0
到
a b c x
1 1 1 1 1
2 1 0 1 2
3 0 0 0 0
不幸的是运行这吐出:
Error in match.fun(FUN) : 'getCode(df[, "a"], df[, "b"], df[, "c"])' is not a function, character or symbol
我是 R 的新手,如果答案过于简单,我深表歉意。谢谢
一些事情:应用将沿着数据框本身(即apply(df, 1, someFunc)
);使用 $
运算符按名称访问列更为惯用。所以如果我有一个名为 df
的数据框和一个名为 a
的列,请使用 df$a
.
在这种情况下,我喜欢沿数据帧的索引执行 sapply
,然后使用该索引从数据帧中获取适当的元素。
df$x <- sapply(1:nrow(df), function(i) getCode(df$a[i], df$b[i], df$c[i]))
正如上面提到的@devmacrile,我只是修改函数,以便能够获得一个包含 3 个元素的向量作为输入,并在你提到的 apply
命令中使用它。
#Example function
getCode <- function (x){
ifelse(x[1]==1 & x[2]==1 & x[3]==1,
1,
ifelse(x[1]==0 & x[2]==0 & x[3]==0,
0,
2)) }
#Create data frame
a = c(1,1,0)
b = c(1,0,0)
c = c(1,1,0)
df <- data.frame(a,b,c)
df
# a b c
# 1 1 1 1
# 2 1 0 1
# 3 0 0 0
# create your new column of results
df$x = apply(df, 1, getCode)
df
# a b c x
# 1 1 1 1 1
# 2 1 0 1 2
# 3 0 0 0 0