![](/img/trans.png)
[英]How to create a new variable (column) based on a combination of row values in R?
[英]how create new variable form multiple column and row condtion in r
如何在 R 中創建具有匹配多個條件的單個數據幀的新變量。 我想從以下數據集創建新變量 (couple_smokr)。 夫婦相關變量不在數據集中,需要從現有變量創建(夫婦將是那些男性和女性具有相似集群,houseno和partnernum的人)。 如果有人有命令來創建這個 (couple_smoke) 變量,我們將不勝感激。
View(afgan)
sex cluster houseno partnernum smoke **couple_smoke**
male 1 4 2 yes yes
female 1 4 2 yes yes
male 1 4 1 no no
male 3 10 1 no no
female 3 10 1 yes no
female 4 4 2 no no
female 4 4 1 no no
male 4 4 3 no no
我猜你定義了couple_smoke
當一對夫婦住在同一個家庭並且他們都吸煙時,這樣除了cluster
、 houseno
和partnernum
houseno
,他們還應該對smoke
變量有相同的輸入。 我說得對嗎?
那么以下應該可以解決問題:首先輸入數據(請下次提供 dput 代碼,如 csgroen 指出的那樣)
afgan <- structure(list(
sex = structure(c(2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L),
.Label = c("female", "male"), class = "factor"),
cluster= c(1, 1, 1, 3, 3, 4, 4, 4),
houseno= c(4, 4, 4, 10, 10, 4, 4, 4),
partnernum= c(2, 2, 1, 1, 1, 2, 1, 3),
smoke = structure(c(1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L),
.Label = c("yes", "no"), class = "factor")),
.Names = c("sex", "cluster", "houseno", "partnernum", "smoke"),
row.names = c(NA, 8L), class = "data.frame")
然后,
library(dplyr)
afgan %>%
group_by(cluster, houseno, partnernum, smoke) %>%
mutate(couple_smoke = ifelse(n() > 1, 1, 0))
dplyr
包的n()
函數計算每組中的行數。
考慮基數 R 的ave()
,其中傳遞一個等於 df 的nrow()
的 1 向量以求和。
df$couple_smoke <- ifelse(ave(rep(1, nrow(df)), df$cluster, df$houseno,
df$partnernum, df$smoke, FUN=sum) > 1, 'yes', 'no')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.