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

问题描述 投票:0回答:1

我有如下所示的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()

谢谢。
dataframe insert tidyverse na na.approx
1个回答
0
投票
欢迎来到!将来,使您的数据更直接可复制粘贴。解决问题的一种方法是使用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

© www.soinside.com 2019 - 2024. All rights reserved.