% fill(Logger) -6ren">
gpt4 book ai didi

r - 我怎样才能 "pad"名称

转载 作者:行者123 更新时间:2023-12-05 08:36:24 35 4
gpt4 key购买 nike

我有一个看起来像这样的 df:

df <- data.frame("Logger" = c("119_1", "1","2","3","119_2","5","6","7","119_3","7","8","9"),
"Temp" =c (4.5, 5.7, 3.8, 8.9, 8.6, 10.5, 11.0, 7.8, 5.6, 7.8, 9.9, 17.3),
"RH" = c(6.5, 2.7, 11.8, 4.9, 3.6, 12.5, 115.0, 3.8, 9.6, 1.8, 3.9,5.3))

但是,我想“填充”变量“Logger”的名称,以便所有数字都被姓氏替换,直到下一个。

所以,基本上我想要这样的输出:

df_desired <- data.frame("Logger" = c("119_1", "119_1","119_1","119_1","119_2","119_2","119_2","119_2","119_3","119_3","119_3","119_3"),
"Temp" =c (4.5, 5.7, 3.8, 8.9, 8.6, 10.5, 11.0, 7.8, 5.6, 7.8, 9.9, 17.3),
"RH" = c(6.5, 2.7, 11.8, 4.9, 3.6, 12.5, 115.0, 3.8, 9.6, 1.8, 3.9,5.3))

我该怎么做?我其实一点头绪都没有。我知道 padr 包存在,但我猜它只适用于日期和 NA。

最佳答案

您可以将没有_的值替换为NA,然后使用fill

library(dplyr)
library(tidyr)

df %>%
mutate(Logger = replace(Logger, !grepl('_', Logger), NA)) %>%
fill(Logger)

# Logger Temp RH
#1 119_1 4.5 6.5
#2 119_1 5.7 2.7
#3 119_1 3.8 11.8
#4 119_1 8.9 4.9
#5 119_2 8.6 3.6
#6 119_2 10.5 12.5
#7 119_2 11.0 115.0
#8 119_2 7.8 3.8
#9 119_3 5.6 9.6
#10 119_3 7.8 1.8
#11 119_3 9.9 3.9
#12 119_3 17.3 5.3

关于r - 我怎样才能 "pad"名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69281363/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com