我目前有一个数据框,看起来像这样:
speed <- c(61,24,3,10,18,19,12,12,7,9)
distance <-c(58,111,92,93,84,103,83,93,88,81)
df <- as.data.frame(cbind(speed, distance))
我想根据速度值将速度变量分为不同的列。例如,对于示例数据框,我希望它看起来像这样:
under50 <- rep(NA,10)
under100<- c(61,3,10,18,12,12,7,9,NA,NA)
under150 <- c(61,24,3,10,18,19,12,12,7,9)
df2 <- as.data.frame(cbind(under50, under100, under150))
我希望它尽可能自动化,因为我有23个数据帧,每个数据帧有100多个行,但不确定从哪里开始。任何帮助将不胜感激!
所以这是另一种方式:
breaks=c(50,100,150)
result <- data.frame(sapply(breaks,function(x)with(df,ifelse(distance<x,speed,NA))))
result <- sapply(result,function(x)c(na.omit(x),rep(NA,sum(is.na(x)))))
colnames(result) <- paste0("under",breaks)
result
# under50 under100 under150
# [1,] NA 61 61
# [2,] NA 3 24
# [3,] NA 10 3
# [4,] NA 18 10
# [5,] NA 12 18
# [6,] NA 12 19
# [7,] NA 7 12
# [8,] NA 9 12
# [9,] NA NA 7
# [10,] NA NA 9
该行:
result <- data.frame(sapply(breaks,function(x)with(df,ifelse(distance<x,speed,NA))))
利用ifelse(...)
函数ro returnspeed
或NA
取决于的值distance
。该行:
result <- sapply(result,function(x)c(na.omit(x),rep(NA,sum(is.na(x)))))
将NA移到末尾。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句