[英]How to assign a value to a column based on value in other column in R data frame or data table
我希望你能在這里幫助我。 我找到了很多基本的重新編碼答案,但沒有一個可以適應我的問題。 問題是:對於所有行,我想將列 Level_eng_1 設置為該行的列 parent_concept 與 ID 列匹配的每一行的 colum verb_e 的值。
我試圖適應 stackoverflow 上存在的眾多解決方案,但沒有成功。
這是數據。
structure(list(ID = c(1, 2, 3, 11, 12, 13, 14, 16, 20, 21, 22,
23, 24, 25, 30, 31, 32, 33, 34), Parent_Concept = c(0L, 0L, 0L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L
), verb_e = c("act", "change", "move", "support", "regulate",
"interact", "structure", "communicate", "time", "make", "decrease",
"increase", "modify", "orientate", "motion", "inhibit", "bring_together",
"separate", "transmit"), Level_eng_1 = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, 19L), class = "data.frame")
所需的輸出是:
structure(list(ID = c(1, 2, 3, 11, 12, 13, 14, 16, 20, 21, 22,
23, 24, 25, 30, 31, 32, 33, 34), Parent_Concept = c(0L, 0L, 0L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L
), verb_e = c("act", "change", "move", "support", "regulate",
"interact", "structure", "communicate", "time", "make", "decrease",
"increase", "modify", "orientate", "motion", "inhibit", "bring_together",
"separate", "transmit"), Level_eng_1 = c("act", "change", "move",
"act", "act", "act", "act", "act", "change", "change", "change",
"change", "change", "change", "move", "move", "move", "move",
"move")), row.names = c(NA, 19L), class = "data.frame")
感謝您的幫助!
可能這會有所幫助
library(dplyr)
input %>%
mutate(Level_eng_1 = verb_e[match(Parent_Concept, ID)],
Level_eng_1 = case_when(is.na(Level_eng_1) ~ verb_e, TRUE ~Level_eng_1))
# ID Parent_Concept verb_e Level_eng_1
#1 1 0 act act
#2 2 0 change change
#3 3 0 move move
#4 11 1 support act
#5 12 1 regulate act
#6 13 1 interact act
#7 14 1 structure act
#8 16 1 communicate act
#9 20 2 time change
#10 21 2 make change
#11 22 2 decrease change
#12 23 2 increase change
#13 24 2 modify change
#14 25 2 orientate change
#15 30 3 motion move
#16 31 3 inhibit move
#17 32 3 bring_together move
#18 33 3 separate move
#19 34 3 transmit move
input <- structure(list(ID = c(1, 2, 3, 11, 12, 13, 14, 16, 20, 21, 22,
23, 24, 25, 30, 31, 32, 33, 34), Parent_Concept = c(0L, 0L, 0L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L
), verb_e = c("act", "change", "move", "support", "regulate",
"interact", "structure", "communicate", "time", "make", "decrease",
"increase", "modify", "orientate", "motion", "inhibit", "bring_together",
"separate", "transmit"), Level_eng_1 = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA,
19L), class = "data.frame")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.