在编写一个计算向量中每个观测值的函数时,我如何引用所述观测值以包括与当前正在操作的观测值相距预定数量的观测值的单元格?如果每一行都是 i,使得 i = 1、2、...等,我如何引用 i-1 行中的列?
这是一个模仿我的困境的示例数据集:
> letters <- c('a', 'b', 'c', 'b', 'e')
> numbers <- c('1', '', '2', '', '3')
> sample <- cbind(letters, numbers)
> sample
letters numbers
[1,] "a" "1"
[2,] "b" ""
[3,] "c" "2"
[4,] "b" ""
[5,] "e" "3"
我想用之前观察sample$numbers
中的值填充每个空单元格。sample$numbers
我如何引用在其创建过程中创建的观察?例如,我尝试过:
> sample$numbers <- ifelse(sample$numbers == "", sample$numbers[as.numeric(rownames(sample)) - 1], sample$numbers)
Error in sample$numbers : $ operator is invalid for atomic vectors
我也尝试使用 common b
insample$letters
来填充缺失值:
> f1 <- function(df, cols, match_with, to_x = 'b'){
+ df[cols] <- lapply(df[cols], function(i)
+ ifelse(grepl(to_x, match_with, fixed = TRUE), sample$numbers[as.numeric(rownames(sample)) - 1],
+ i))
+ return(df)
+ }
> sample = f1(sample, cols = c('numbers'), match_with = sample$letters)
Hide Traceback
Rerun with Debug
Error in sample$letters : $ operator is invalid for atomic vectors
5.
grepl(to_x, match_with, fixed = TRUE)
4.
ifelse(grepl(to_x, match_with, fixed = TRUE), sample$numbers[as.numeric(rownames(sample)) -
1], i)
3.
FUN(X[[i]], ...)
2.
lapply(df[cols], function(i) ifelse(grepl(to_x, match_with, fixed = TRUE),
sample$numbers[as.numeric(rownames(sample)) - 1], i))
1.
f1(sample, cols = c("numbers"), match_with = sample$letters)
在这两种情况下,我的麻烦似乎是我在之前的观察中sample$numbers[as.numeric(rownames(sample)) - 1]
用来引用sample$numbers
' 值。有一个更好的方法吗?