编辑:如何在 R 中的特定字符值之间插入 NA
EDITED: How to insert NAs between specific character values in R
我有一个带有虚拟字符 "break" 的值列表,编码为表示换行符:
[11] "break" "-9.737715" "0.000091" "-0.000340" "-0.001318"
[16] "-38.103233" "-10.327046" "break" "27.469583" "break"
我需要:1) 计算每次出现 "break" 之间的字符数,以及 2) 将 NA 插入不符合指定字符数 (= 9) 的字符串中。例如,我上面代码的理想输出是:
[11] "break" "-9.737715" "0.000091" "-0.000340" "-0.001318"
[16] "-38.103233" "-10.327046" "NA" "NA" "NA"
[21] "break" "27.469583" "NA" "NA" "NA"
[26] "NA" "NA" "NA" "NA" "NA"
[31] "break"
无法在任何地方找到解决方案...感谢帮助!
这 几乎 您要问的是 - 它在最后一次休息后添加了一组 NA。 (如果你知道最后一个条目是中断,那么你可以在计算中断之前将其删除。如果最后一个条目不是中断,它应该有效。)
x <- c("break" ,"-9.737715", "0.000091", "-0.000340", "-0.001318", "-38.103233", "-10.327046", "break" , "27.469583", "break")
count_breaks = cumsum(x == "break")
unlist(tapply(x, count_breaks, function(.x) {
c(.x, rep(NA, 10 - length(.x)))
}))
其中一种方法可能是
y <- c()
cnt_betwn_break <- 0
for(i in 1:length(a)){
ifelse(a[i]=='break',
{if(!(cnt_betwn_break %in% c(0,9))) y <- c(y, rep(NA, 9 - cnt_betwn_break))
cnt_betwn_break <- 0},
cnt_betwn_break <- cnt_betwn_break + 1)
y <- c(y, a[i])
}
y
# [1] "break" "-9.737715" "0.000091" "-0.000340" "-0.001318" "-38.103233" "-10.327046" NA
# [9] NA NA "break" "27.469583" NA NA NA NA
#[17] NA NA NA NA "break"
示例数据:
a <- c("break", "-9.737715", "0.000091", "-0.000340", "-0.001318", "-38.103233", "-10.327046", "break", "27.469583", "break")
我有一个带有虚拟字符 "break" 的值列表,编码为表示换行符:
[11] "break" "-9.737715" "0.000091" "-0.000340" "-0.001318"
[16] "-38.103233" "-10.327046" "break" "27.469583" "break"
我需要:1) 计算每次出现 "break" 之间的字符数,以及 2) 将 NA 插入不符合指定字符数 (= 9) 的字符串中。例如,我上面代码的理想输出是:
[11] "break" "-9.737715" "0.000091" "-0.000340" "-0.001318"
[16] "-38.103233" "-10.327046" "NA" "NA" "NA"
[21] "break" "27.469583" "NA" "NA" "NA"
[26] "NA" "NA" "NA" "NA" "NA"
[31] "break"
无法在任何地方找到解决方案...感谢帮助!
这 几乎 您要问的是 - 它在最后一次休息后添加了一组 NA。 (如果你知道最后一个条目是中断,那么你可以在计算中断之前将其删除。如果最后一个条目不是中断,它应该有效。)
x <- c("break" ,"-9.737715", "0.000091", "-0.000340", "-0.001318", "-38.103233", "-10.327046", "break" , "27.469583", "break")
count_breaks = cumsum(x == "break")
unlist(tapply(x, count_breaks, function(.x) {
c(.x, rep(NA, 10 - length(.x)))
}))
其中一种方法可能是
y <- c()
cnt_betwn_break <- 0
for(i in 1:length(a)){
ifelse(a[i]=='break',
{if(!(cnt_betwn_break %in% c(0,9))) y <- c(y, rep(NA, 9 - cnt_betwn_break))
cnt_betwn_break <- 0},
cnt_betwn_break <- cnt_betwn_break + 1)
y <- c(y, a[i])
}
y
# [1] "break" "-9.737715" "0.000091" "-0.000340" "-0.001318" "-38.103233" "-10.327046" NA
# [9] NA NA "break" "27.469583" NA NA NA NA
#[17] NA NA NA NA "break"
示例数据:
a <- c("break", "-9.737715", "0.000091", "-0.000340", "-0.001318", "-38.103233", "-10.327046", "break", "27.469583", "break")