我有这样的数据
df<- structure(list(V1 = c(0.7, 2.083, 2.517, 2.667, 3.883, NA, NA,
NA), V2 = c(1.4, 1.65, 2.1, 2.267, 3.017, 3.383, NA, NA), V3 = c(0.85,
1.633, 2.117, 2.267, 3.567, 5.35, 9.7, 15.867), V4 = c(1.6, 1.9,
2.117, 2.3, 9.717, 21.6, NA, NA)), .Names = c("V1", "V2", "V3",
"V4"), class = "data.frame", row.names = c(NA, -8L))
# V1 V2 V3 V4
#1 0.700 1.400 0.850 1.600
#2 2.083 1.650 1.633 1.900
#3 2.517 2.100 2.117 2.117
#4 2.667 2.267 2.267 2.300
#5 3.883 3.017 3.567 9.717
#6 NA 3.383 5.350 21.600
#7 NA NA 9.700 NA
#8 NA NA 15.867 NA
我首先得到奇数列
odd <- seq(1, ncol(df), by = 2)
然后我像这样从
创建一个新的数据框mdf <- df[,odd]
然后我将它们排序并将它们放在一列中
newdf <- data.frame(Acol1= sort(unname(unlist(mdf))))
# Acol1
#1 0.700
#2 0.850
#3 1.633
#4 2.083
#5 2.117
#6 2.267
#7 2.517
#8 2.667
#9 3.567
#10 3.883
#11 5.350
#12 9.700
#13 15.867
现在我想把偶数列中的每个元素放在那些奇数列的前面。所以我的输出将是这样的 这意味着第1列是第2列,第3列是第4列等。 所以空位可以由ZERO或NA填充,甚至可以保持空白。
# Acol1 V2 V4
#1 0.700 1.400
#2 0.850 1.600
#3 1.633 1.900
#4 2.083 1.650
#5 2.117 2.117
#6 2.267 2.300
#7 2.517 2.100
#8 2.667 2.267
#9 3.567 9.717
#10 3.883 3.017
#11 5.350 21.600
#12 9.700
#13 15.867
答案 0 :(得分:2)
这是一个建议:
new_df$V2<-apply(new_df,MARGIN = 1, function(z){
w<-which(as.numeric(as.character(z)) == df[,1])
if(length(w)){
return(df[w,2])
}
else{ return(NA)}
}
)
new_df$V3<-apply(new_df,MARGIN = 1, function(z){
w<-which(as.numeric(as.character(z)) == df[,3])
if(length(w)){
return(df[w,4])
}
else{ return(NA)}
}
)
for(i in 1:nrow(result)){
val<-newdf[i,1]
w<-which(sapply(odd,function(y){
sum(val==df[,y],na.rm = TRUE)>0
}
))## in which column does the value appear?
result[i,w]<-sapply(w,function(z){
df[which(df[,odd[z]]==val),odd[z]+1]
}
) ### this might not work if the value in one odd column appears more than once
}
result<-cbind(newdf,result)
答案 1 :(得分:2)
这是: 我们首先创建一个函数
f1 <- function(x,y){
x[match(newdf$Acol1, y)]
}
然后我们使用mapply
,
mapply(f1, df[,c(FALSE, TRUE)], df[,c(TRUE, FALSE)])
# V2 V4
#[1,] 1.400 NA
#[2,] NA 1.600
#[3,] NA 1.900
#[4,] 1.650 NA
#[5,] NA 2.117
#[6,] NA 2.300
然后您可以cbind
照常输出newdf