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
697 views
in Technique[技术] by (71.8m points)

r - Assign value to group based on condition in column

I have a data frame that looks like the following:

> df = data.frame(group = c(1,1,1,2,2,2,3,3,3), 
                 date = c(1,2,3,4,5,6,7,8,9),
                 value = c(3,4,3,4,5,6,6,4,9))
> df
  group date value
1     1    1     3
2     1    2     4
3     1    3     3
4     2    4     4
5     2    5     5
6     2    6     6
7     3    7     6
8     3    8     4
9     3    9     9

I want to create a new column that contains the date value per group that is associated with the value "4" from the value column.

The following data frame shows what I hope to accomplish.

  group date value newValue
1     1    1     3        2
2     1    2     4        2
3     1    3     3        2
4     2    4     4        4
5     2    5     5        4
6     2    6     6        4
7     3    7     6        8
8     3    8     4        8
9     3    9     9        8

As we can see, group 1 has the newValue "2" because that is the date associated with the value "4". Similarly, group two has newValue 4 and group three has newValue 8.

I assume there is an easy way to do this using ave() or a range of dplyr/data.table functions, but I have been unsuccessful with my many attempts.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Here's a quick data.table one

library(data.table)
setDT(df)[, newValue := date[value == 4L], by = group]
df
#    group date value newValue
# 1:     1    1     3        2
# 2:     1    2     4        2
# 3:     1    3     3        2
# 4:     2    4     4        4
# 5:     2    5     5        4
# 6:     2    6     6        4
# 7:     3    7     6        8
# 8:     3    8     4        8
# 9:     3    9     9        8

Here's a similar dplyr version

library(dplyr)
df %>%
  group_by(group) %>%
  mutate(newValue = date[value == 4L])

Or a possible base R solution using merge after filtering the data (will need some renaming afterwards)

merge(df, df[df$value == 4, c("group", "date")], by = "group")

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

...