I have a function which I need to extract a column, when I use dataframe$column1[i], the function returns an error, but when I use dataframe[, column1][i], it will work. Why can't I just use dataframe$column vs dataframe[, column]???
function1 <- function(data, x, y) {
data <- arrange(data, x)
ylist <- NULL
for(i in 1:nrow(data)){
x0 <- data[, x][i]
data$d0 <- abs(data[,x] - x0)
yi <- data %>% arrange(d0) %>% select(y) %>% unlist() %>% mean()
ylist <- c(ylist, yi)
}
return(ylist)
}
If I wrote the function this way below, it'll return an error: Error in $<-.data.frame
(*tmp*
, "d0", value = numeric(0)) : replacement has 0 rows, data has 500
function1 <- function(data, x, y) {
data <- arrange(data, x)
ylist <- NULL
for(i in 1:nrow(data)){
x0 <- data$x[i]
data$d0 <- abs(data$x - x0)
yi <- data %>% arrange(d0) %>% select(y) %>% unlist() %>% mean()
ylist <- c(ylist, yi)
}
return(ylist)
}