R数据表:如何在特定单元格正下方查找未知数量的空单元格,并用带编号的字符串填充它们 [英] R data table : How to find unknown number of empty cells directly below a specific cell and fill them with numbered strings
问题描述
我知道如何通常在 data.table
中找到空的单元格
,但这有点棘手。而且我还没有弄清楚如何解决这个问题。
I know how to find empty cells
in a data.table
in general, but this is a little trickier and I haven't quite figured out how to manage this.
我说我有一个 data.table
,它在 df [2,1]中
包含我需要定位的关键字字符串:智能触发!在这种情况下。
Lets say I have a data.table
which in df[2,1]
contains my keyword string i need to target: "Smart triggered!" in this case.
仪器用户使用的智能触发器的数量可以变化,但是会导致 df [2,1]以下的1个空白单元格
每个触发器,以及它们在第二个列中的名称
The amount of smart triggers used by the user of the instrument can vary, but they result in 1 empty cell below df[2,1]
for each trigger, and their name in the 2nd column
以便找出智能触发!正下方有多少空的单元格
。并依次向其填充智能触发器1,智能触发器2 ...,直到我们点击列$ c中的下一个
单元格
I'm looking for a way to figure out how many empty cells
are directly below "Smart triggered!" and fill them sequentially with "Smart trigger 1", Smart trigger 2"... until we hit the first next cell
in column
1 that contains something ('Instrument'). There are potential other empty cells further down in the table that I do not want to alter.
$ c> 1包含某些内容( Instrument),表中还有其他不希望更改的空单元格。我的信息文件读入 data.table
像这样:
In this case my info files read into a data.table
looking like this:
df <- data.frame(name = c("Trigger", "Smart Triggered!", "", "", "Instrument", "Beam", "Core speed", "Channel1", "Channel2", "Channel3", "Channel4", ""),
values = c("SWS", "", "FLRED", "FLORANGE", "Demo", "5um", "2.2", "FWS", "SWS", "FLRED", "FLORANGE", "x"))
我怀疑while循环,但可能有比这更好的数据表解决方案。
I suspect perhaps a while loop, but there are probably better data table solutions than that.
查看是否适合您:
library(tidyverse)
df <- data.frame(name = c("Trigger", "Smart Triggered!", "", "", "Instrument", "Beam", "Core speed", "Channel1", "Channel2", "Channel3", "Channel4", ""),
values = c("SWS", "", "FLRED", "FLORANGE", "Demo", "5um", "2.2", "FWS", "SWS", "FLRED", "FLORANGE", "x"))
df %>%
mutate(new_name = ifelse(as.character(name) == "", NA, as.character(name))) %>%
tidyr::fill(new_name) %>%
split(.$new_name) %>%
map_df(., ~.x %>% mutate(row_no = row_number(),
row_no = lag(row_no),
new_name1 = ifelse(is.na(row_no),
as.character(new_name),
paste0(as.character(new_name), "_", row_no)))) %>%
select(name, new_name, new_name1, values) %>%
full_join(df, .) %>%
mutate(name = as.character(name)) %>%
mutate(name = ifelse(new_name == "Smart Triggered!", new_name1, name)) %>%
select(name, values)
这篇关于R数据表:如何在特定单元格正下方查找未知数量的空单元格,并用带编号的字符串填充它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!