简体   繁体   English

如何使用 R 中的条件更新列名的值?

[英]How to update values with the column names with condition in R?

I have a data frame like below.我有一个如下所示的数据框。

Note: This is the sample data of my data.
data:
id user   time1    time2    time3  
1  user1  07:52    08:34    08:43
2  user2  08:14    10:09    10:22
3  user3  07:43    09:29    09:44
4  user4  09:36    10:34    11:05

Now I want to check how many active users are available at the time 09:36.现在我想检查 09:36 时有多少活跃用户可用。 I have wrote condition like below to get active users at the time 09:36.我写了如下条件,以便在 09:36 时获得活跃用户。

for(k in 1:nrow(data)){
   k=4
   active_users_data <- subset(data,(data$time2 < data$time1[k] &
                                  data$time3> data$time1[k]))
}
output :
id user   time1    time2    time3  
3  user3  07:43    09:29    09:44

But I need output format like below:但我需要 output 格式,如下所示:

id time1    time2    time3  user1   user2   user3  user4 
3  07:43    09:29    09:44    0       0       1      0

That is if user3 active at that point of time I need to get 1 in user3 column.How can i achieve the output like above?也就是说,如果 user3 在那个时间点处于活动状态,我需要在 user3 列中获得 1。我怎样才能实现上面的 output? If two users are active at that point of time I need to get 1 corresponding users column.Please,suggest me ideas.如果当时有两个用户处于活动状态,我需要获得 1 个相应的用户列。请给我建议。 I have to do this for large data set.我必须为大型数据集执行此操作。

perfect for a tidyverse完美的tidyverse

library(tidyverse)
k=as.POSIXct(strptime("09:36", "%H:%M"))
df %>% 
  mutate_at(vars(contains("time")), ~as.POSIXct(strptime(., "%H:%M"))) %>% 
  mutate(t2 = ifelse(time2 < k & time3 > k, 1, 0)) %>% 
  spread(user, t2, fill = 0)
  id               time1               time2               time3 user1 user2 user3 user4
1  1 2020-05-08 07:52:00 2020-05-08 08:34:00 2020-05-08 08:43:00     0     0     0     0
2  2 2020-05-08 08:14:00 2020-05-08 10:09:00 2020-05-08 10:22:00     0     0     0     0
3  3 2020-05-08 07:43:00 2020-05-08 09:29:00 2020-05-08 09:44:00     0     0     1     0
4  4 2020-05-08 09:36:00 2020-05-08 10:34:00 2020-05-08 11:05:00     0     0     0     0

I transformed the times into datetimes (there could be a better option, but I'm not an date expert), finally I used spread to make the data wide.我将时间转换为日期时间(可能有更好的选择,但我不是日期专家),最后我使用传播来扩大数据范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM