我有兩個資料框:
df1 <- data.frame(Q1 = rep(c(0, 1), 3),
Q2 = rep(c(1, 0), 3),
Q3 = rep(1, 6))
df2 <- data.frame(Q1 = rep(c(0, 1, 2), 2),
Q2 = rep(c(2, 1, 0), 2),
Q3 = c(rep(1, 3), rep(2, 3)))
> df1
Q1 Q2 Q3
1 0 1 1
2 1 0 1
3 0 1 1
4 1 0 1
5 0 1 1
6 1 0 1
> df2
Q1 Q2 Q3
1 0 2 1
2 1 1 1
3 2 0 1
4 0 2 2
5 1 1 2
6 2 0 2
現在,我想根據這兩個資料框創建一個新的資料框,并根據以下條件填充條目:
| 新條目 | (健康)狀況 |
|---|---|
| 6 | if(df1 == 1 & df2 == 2) |
| 5 | if(df1 == 1 & df2 == 1) |
| 4 | if(df1 == 1 & df2 == 0) |
| 3 | if(df1 == 0 & df2 == 0) |
| 2 | if(df1 == 0 & df2 == 1) |
| 1 | if(df1 == 0 & df2 == 2) |
我的問題是我不知道如何同時運行兩個資料框來修改它們或創建一個新的資料框。我可憐的嘗試看起來像:
df3 <- modify(df1, function(x) ifelse(x == 1 & df2[x] == 2, 6,
ifelse(x == 1 & df2[x] == 1, 5,
ifelse(x == 1 & df2[x] == 0, 4,
ifelse(x == 0 & df2[x] == 0, 3,
ifelse(x == 0 & df2[x] == 1, 2, 1))))))
我知道這永遠不會奏效,但這是我能做到的最好的。有誰知道如何解決這個問題?非常感謝!
uj5u.com熱心網友回復:
您應該直接使用資料框名稱:
df3 <- ifelse(df1 == 1 & df2 == 2, 6,
ifelse(df1 == 1 & df2 == 1, 5,
ifelse(df1 == 1 & df2 == 0, 4,
ifelse(df1 == 0 & df2 == 0, 3,
ifelse(df1 == 0 & df2 == 1, 2, 1)))))
否則,這里有一個基于 R 的系統解決方案:
#Create new dataframe from df1 and df2 pasted element by element
df <- mapply(paste, df1, df2)
#Create a lookup table,
l <- setNames(1:6, paste(rep(0:1, each = 3), c(2:0, 0:2)))
# 0 2 0 1 0 0 1 0 1 1 1 2
# 1 2 3 4 5 6
#Match values of df and the lookup
df[] <- l[match(df, names(l))]
#Convert to dataframe
as.data.frame(df)
# Q1 Q2 Q3
# 1 3 6 5
# 2 5 2 5
# 3 1 4 5
# 4 4 1 6
# 5 2 5 6
# 6 6 3 6
uj5u.com熱心網友回復:
res <- matrix(nrow = nrow(df1), ncol = ncol(df1))
res[df1 == 1 & df2 == 2] <- 6
res[df1 == 1 & df2 == 1] <- 5
res[df1 == 1 & df2 == 0] <- 4
res[df1 == 0 & df2 == 0] <- 3
res[df1 == 0 & df2 == 1] <- 2
res[df1 == 0 & df2 == 2] <- 1
print(res)
[,1] [,2] [,3]
[1,] 3 6 5
[2,] 5 2 5
[3,] 1 4 5
[4,] 4 1 6
[5,] 2 5 6
[6,] 6 3 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/521246.html
