提前为初学者的问题道歉,但我暂时不喜欢R。 我正在定义一个在数据框上运行摘要统计信息的函数,其内容如下:
sumstats = function(y) {
sumst = sapply(y, function(x) {
sumstat = c(
mean(x, na.rm = TRUE),
median(x, na.rm = TRUE),
sd(x, na.rm = TRUE),
min(x, na.rm = TRUE),
max(x, na.rm = TRUE)
) names(sumstat) = c("Mean", "Median", "SD", "Min", "Max") sumstat
}) aperm(sumst)
}
但是,我仍然收到以下错误,表明我要定义不同列的名称的方式出了问题:
Error: unexpected symbol in:
" max(x, na.rm = TRUE)
) names"
您能告诉我我的语法引发错误吗?
谢谢
答案 0 :(得分:1)
您需要在sumstat的)和namessumsum的)之间添加新行,例如
sumstats = function(y) {
sumst = sapply(y, function(x) {
c(
mean(x, na.rm = TRUE),
median(x, na.rm = TRUE),
sd(x, na.rm = TRUE),
min(x, na.rm = TRUE),
max(x, na.rm = TRUE)
)
names(sumstat) = c("Mean", "Median", "SD", "Min", "Max")
sumstat
})
aperm(sumst)
}
您还可以命名矢量中的项目,并完全跳过名称(sumstat)
sumstats = function(y) {
sapply(y, function(x) {
sumstat = c(
Mean = mean(x, na.rm = TRUE),
Median = median(x, na.rm = TRUE),
sd = sd(x, na.rm = TRUE),
Min = min(x, na.rm = TRUE),
Max = max(x, na.rm = TRUE)
)
})
aperm(sumst)
}
答案 1 :(得分:0)
您将在names
结束的同一行上启动c
函数。只需更改代码的格式即可。
请注意,使用<-
将事物分配给对象更安全。 =
用于将值传递给函数参数。
sumstats <- function(y) {
sumst <- sapply(
y,
function(x) {
sumstat <- c(
mean(x, na.rm = TRUE),
median(x, na.rm = TRUE),
sd(x, na.rm = TRUE),
min(x, na.rm = TRUE),
max(x, na.rm = TRUE)
)
names(sumstat) <- c("Mean", "Median", "SD", "Min", "Max")
return(sumstat)
}
)
aperm(sumst)
}