And*_*rew -1 statistics r
我有一个数据集存储在一个文本文件中,其格式为值的值,后跟计数,如下所示:
var_a 1:5 5:12 7:9 9:14 ...
Run Code Online (Sandbox Code Playgroud)
表明var_a在数据集中取值1 5次,5 12次,等等.每个变量在该格式中都是自己的行.
我希望能够在R中对此数据集执行计算,例如分位数,方差等.有没有一种简单的方法从文件加载数据并计算这些统计数据?最后,我想为每个变量制作一个盒子和胡须图.
干杯!
您可以使用readLines读入数据文件
.x <- readLines(datafile)
Run Code Online (Sandbox Code Playgroud)
我将创建一些虚拟数据,因为我没有该文件.这应该相当于输出readLines
## dummy
.x <- c("var_a 1:5 5:12 7:9 9:14", 'var_b 1:5 2:12 3:9 4:14')
Run Code Online (Sandbox Code Playgroud)
我按间距分开得到每个
#split by space
space_split <- strsplit(.x, ' ')
# get the variable names (first in each list)
variable_names <- lapply(space_split,'[[',1)
# get the variable contents (everything but the first element in each list)
variable_contents <- lapply(space_split,'[',-1)
# a function to do the appropriate replicates
do_rep <- function(x){rep.int(x[1],x[2])}
# recreate the variables
variables <- lapply(variable_contents, function(x){
.list <- strsplit(x, ':')
unlist(lapply(lapply(.list, as.numeric), do_rep))
})
names(variables) <- variable_names
Run Code Online (Sandbox Code Playgroud)
您可以使用获得每个变量的方差
lapply(variables, var)
## $var_a
## [1] 6.848718
##
## $var_b
## [1] 1.138462
Run Code Online (Sandbox Code Playgroud)
或获得箱图
boxplot(variables, ~.)
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |