我有以下資料集:
hairdf=data.frame(
id=c(1:4),
typedad=c("straight*","curly"),
colourdad=c("brown","black"),
typemom=c("curly","wavy*"),
colourmom=c("blonde","red"),
typekid1=c("wavy","mixed*"),
colourkid1=c("black","blonde"))
我想創建新的列來查看頭發型別,如果頭發型別出現在沒有星號的“頭發型別”列中,則為值 1;如果帶有星號,則為值 2(如果它沒有出現在該行中,則為空白)。它應該是這樣的:
| ID | 打字爸爸 | 彩色爸爸 | 打字媽媽 | 色彩媽媽 | 型別kid1 | 彩色孩子1 | 直的 | 卷曲 | 波浪狀的 | 混合 |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 直* | 棕色的 | 卷曲 | 金發女郎 | 波浪狀的 | 黑色的 | 2 | 1 | 1 | |
| 2 | 卷曲 | 黑色的 | 波浪狀的* | 紅色的 | 混合* | 金發女郎 | 1 | 2 | 2 |
我的兩個問題是所有其他示例都使用數值,所有其他示例的感興趣的列彼此相鄰。我需要看起來匹配列中的字串的代碼,這些列可以位于資料框中的任何位置。我嘗試了以下方法:
straight<- hairdf %>% mutate(across(c("hairtypedad", "hairtypemom", "hairtypekid1"),
ifelse(.=="straight", 1
ifelse(.=="straight*",2, ""
))))
curly<- hairdf %>% mutate(across(c("hairtypedad", "hairtypemom", "hairtypekid1"),
ifelse(.=="curly", 1
ifelse(.=="curly*",2, ""
wavy<- hairdf %>% mutate(across(c("hairtypedad", "hairtypemom", "hairtypekid1"),
ifelse(.=="wavy", 1
ifelse(.=="wavy*",2, ""
))))
mixed<- hairdf %>% mutate(across(c("hairtypedad", "hairtypemom", "hairtypekid1"),
ifelse(.=="mixed", 1
ifelse(.=="mixed*",2, ""
))))
但我不確定這段代碼是否有意義。此外,這將是乏味的,因為我有更多的發型,所以任何使它更容易的建議也將不勝感激!謝謝!!!
uj5u.com熱心網友回復:
這不是更有效的答案,也不是更一般的解決方案,但可能滿足解決方案:
#create columns
st <- rep(NA,nrow(hairdf));
cur <- rep(NA,nrow(hairdf));
wav <- rep(NA,nrow(hairdf));
mix <- rep(NA,nrow(hairdf));
#join and define words
hairdf <- cbind(hairdf,st,cur,wav,mix);
words <- c("straight","curly","wavy","mixed");
words_ast <- paste(words,"*",sep=""); #just get the "*" words
#make a loop according to positions of columns st,cur,wav,mix
for (j in 1:length(words_ast)){ #let's see if we can evaluate 2 in words_ast
for (i in c(2,3,4)){ #but only in columns we selected
a <- subset(hairdf,hairdf[,i]==words_ast[j]) #subset columns which satisfay condition. [Note that this can be written as hairdf %>% subset(.[,i]==words_ast[j]) ]
hairdf[row.names(a),7 j] <- 2 #replace value from column 8
}
}
#repeat process for "words"
for (j in 1:length(words)){
for (i in c(2,3,4)){
a <- subset(hairdf,hairdf[,i]==words[j])
hairdf[row.names(a),7 j] <- 1
}
}
這應該可以讓您獲得預期的結果。或者,您可以使用該assign()功能,即
assign(x,value=1)
其中 x 是單詞中的每個元素。
所以在一個回圈中:
assign(words[n],value=1) ; assign(words_ast[n],value=2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/433805.html
上一篇:IF陳述句不接受引數-電子表格
下一篇:通過a-tag按鈕選擇下拉值
