在特定列中插入一行具有相同常数值的行(Rstudio)

时间:2019-11-21 11:02:05

标签: r tidyverse

我的df如下:3列9行。

  device voltage current
1  north       1       1
2  north       2       2
3  north       3       3
4   west       1      10
5   west       2      20
6   west       3      30
7 center       1     100
8 center       2     200
9 center       3     300

如何为每个设备组插入恒定的新电流值? (例如新的当前值= 75)?这就是我想要获得的

   device voltage current
1   north       1       1
2   north       2       2
3   north       3       3
4   north      NA      75
5    west       1      10
6    west       2      20
7    west       3      30
8    west      NA      75
9  center      NA      75
10 center       1     100
11 center       2     200
12 center       3     300

我希望“ voltage”变量获得NA值,以便将来可以使用na.approx进行插值。 多谢您的协助。 我尝试过此操作(在其他地方也看到过),但没有成功。

df %>% 
  split(.$current) %>% 
  map(~add_row(., device = (.$device), current = 75, votage = NA)) %>% 
  bind_rows()

谢谢。

2 个答案:

答案 0 :(得分:1)

欢迎您!将来,使您的数据更直接可复制粘贴。解决问题的一种方法是使用group_by中的dodplyr。解决方案如下:

library(tidyverse)

df <- tibble(
  device = rep(c("north", "west", "center"), each = 3),
  voltage = rep(1:3, times = 3),
  current = c(1, 2, 3, 10, 20, 30, 100, 200, 300)
)

df %>% 
  group_by(device) %>% 
  do(add_row(., device = .$device[1], current = 75))

或者,如果您更喜欢purrr

df %>% 
  split(.$device) %>% 
  imap(~add_row(.x, device = .y, current = 75)) %>% 
  bind_rows()

哪个生产:

# A tibble: 12 x 3
# Groups:   device [3]
   device voltage current
   <chr>    <int>   <dbl>
 1 center       1     100
 2 center       2     200
 3 center       3     300
 4 center      NA      75
 5 north        1       1
 6 north        2       2
 7 north        3       3
 8 north       NA      75
 9 west         1      10
10 west         2      20
11 west         3      30
12 west        NA      75

答案 1 :(得分:0)

欢迎来到。

使用full_join的解决方案,它可以处理NA中的voltage值:

library(tidyverse)

df <- tibble(
  device = rep(c("north", "west", "center"), each = 3),
  voltage = rep(1:3, times = 3),
  current = c(1, 2, 3, 10, 20, 30, 100, 200, 300)
)

# new dataframe, with one row for each value of device:
new_df <- df %>%
  select(device) %>%
  unique() %>%
  mutate(current = 75)

df %>%
  full_join(new_df)