我想獲取資料框中特定列的平均值并將這些平均值存盤在 R 中的向量中。
列的特定變數名稱存盤在向量中。對于那些特定的變數(取決于用戶輸入),我想計算平均值并將它們存盤在一個向量中,我可以在該向量上回圈然后在我的代碼的另一部分中使用它。
我嘗試如下,例如:
specific_variables <- c("variable1", "variable2") # can be of a different length depending on user input
data <- data.frame(...) # this is a dataframe with multiple columns, of which "variable1" and "variable2" are both columns from
mean_xm <- 0 # empty variable for storage purposes
# for loop over the variables
for (i in length(specific_variables)) {
mean_xm[i] <- mean(data$specific_variables[i], na.rm = TRUE)
}
print(mean_xm)
我收到一條錯誤訊息
Error: object of type 'closure' is not subsettable
使用 sapply 的第二次嘗試:
colMeans(data[sapply(data, is.numeric)])
但這給了我資料框所有列的方法,但我只想從specific_variables. 理想情況下,我想像第一次嘗試那樣將這些方法存盤到向量中。
uj5u.com熱心網友回復:
我們可能會使用
v1 <- unname(colMeans(data[specific_variables], na.rm = TRUE))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520691.html
標籤:r循环向量意思是应用
