Hi Everyone,
I wrote an R function, when I call the function, it gave me the following error message:
wtMedian <- function(data, n){
chr <- unique(data[, which(colnames(data)=="chromosome")])
df <- data.frame(Col1 = character(),
Col2 = integer(),
Col3 = integer(),
Col4 = character(),
Col5 = double(),
Col6 = double(),
Col7 = double(), stringsAsFactors = FALSE)
weighted_m <- c() # new vector to store weighted median
for (ch in chr){
data1 <- data %>% filter(chromosome %in% ch) # subset certain chromosome
# nch <- length(data1$log2) # the $ will cause error when calling the function
nch <- length(data1[,which(colnames(data)=="log2")])
for (i in c(1:n)){
#m <- median(data1[c(1:(n+i-1)),6])
dat <- data1[c(1:(n+i-1)), which(colnames(data1)=="log2")] # data set for calculating weighed median
w <- data1[c(1:(n+i-1)), which(colnames(data1)=="weight")] # weight set for calculating weighted median
m <- weightedMedian(dat,w) # calculate weighted median
weighted_m <- append(weighted_m, m)
}
for (i in c((n+1):(nch-n))){
dat <- data1[c((i-n):(i+n-1)), which(colnames(data1)=="log2")]
w <- data1[c((i-n):(i+n-1)), which(colnames(data1)=="weight")]
m <- weightedMedian(dat,w)
weighted_m <- append(weighted_m, m)
}
for (i in c((nch-n+1):nch)){
dat <- data1[c((i-n):nch), which(colnames(data1)=="log2")]
w <- data1[c((i-n):nch), which(colnames(data1)=="weight")]
m <- weightedMedian(dat,w)
weighted_m <- append(weighted_m, m)
}
df <- rbind(df, data1)
}
df$log2 <- weighted_m #assign weighted median to original dataframe
return(df)
}
df <- wtMedian(data,25)
Question2:
when I use $ in the function, there will be an error when calling the function, for example, if I replaced
chr <- unique(data[, which(colnames(data)=="chromosome")])
with
chr <- unique(data$chromosome). # the error message will be :
Error: [: $ operator is invalid for atomic vectors].
I used r which()
to avoid that error, but causing the first error as mentioned.
However, if I don't run the above code in a function, everything will be fine.
Can anyone help me with the troubleshooting and explain what cause these errors, and why this specifically occurred in functions?
Greatly appreciated your help.
Best,
Lc