我需要为初学者使用 R *apply 函数制作教程(第一次不使用 reshape 或 plyr 包)
我试着lapply
(因为我读了apply
对于数据框不好)这个数据框的一个简单函数,我想使用命名列来访问数据:
fDist <- function(x1,x2,y1,y2) {
return (0.1*((x1 - x2)^2 + (y1-y2)^2)^0.5)
}
data <- read.table(textConnection("X1 Y1 X2 Y2
1 3.5 2.1 4.1 2.9
2 3.1 1.2 0.8 4.3
"))
data$dist <- lapply(data,function(df) {fDist(df$X1 , df$X2 , df$Y1 , df$Y2)})
我有这个错误$ operator is invalid for atomic vectors
,这可能是因为数据框被 laply 修改了?...有没有最好的方法来使用 $ 命名列来做到这一点?
我用@DWin 的答案解决了我的第一个问题。但我还有另一个问题,即混合数据框(数字+字符)的误解:
在我的新用例中,我使用两个函数来计算距离,因为我的目标是比较所有其他点之间的距离点。
data2 <- read.table(textConnection("X1 Y1 X2 Y2
1 3.5 2.1 4.1 2.9
2 3.1 1.2 0.8 4.3
"))
data2$char <- c("a","b")
fDist <- function(x1,y1,x2,y2) {
return (0.1*((x1 - x2)^2 + (y1-y2)^2)^0.5)
}
fDist2 <- function(fixedX,fixedY,vec) {
fDist(fixedX,fixedY,vec[['X2']],vec[['Y2']])
}
# works with data (dataframe without character), but not with data2 (dataframe with character)
#ok
data$f_dist <- apply(data, 1, function(df) {fDist2(data[1,]$X1,data[1,]$Y1,df)})
#not ok
data2$f_dist <- apply(data2, 1, function(df) {fDist2(data2[1,]$X1,data2[1,]$Y1,df)})