Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

dataframe - Set values for a group based on a value for a specific group member

I have a list of people grouped by schedule, house and, family. Each person has an ID and a code (showing their status; head of a household or otherwise) and occupation. I need to add one more column, the value in which would for each person equal the occupational code of the head of their household. I have tried:

id <- c(1:10)
schedule <- c(1,1,1,1,1,2,2,2,2,2)
house <- c(1,1,1,2,2,1,1,1,1,2)
status <- c(10,20,30,20,10,20,20,10,30,10)
occup <- c(1,2,3,3,5,2,2,4,5,1)
census <- data.frame(id, schedule, house, status, occup)

for(a in 1:max(census$schedule))
{
hh1 <- census %>% filter(schedule == a)
for(b in 1:max(census$house))
{
hh2 <-  hh1 %>% filter(house == b)
head <- hh2 %>% filter(status == 20)
x <- head$occup
mutate(hh2, h_occ = x)
}}

But got an error message:

Error: Problem with mutate() input h_occ. x Input h_occ can't be recycled to size 4. i Input h_occ is x. i Input h_occ must be size 4 or 1, not 2.

I do not know how to resolve this issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...