r - 用于提取 ESS 数据的 R 函数,“找不到函数粘贴”
问题描述
从“essurvey”包中,我有一个数据集(作为“列表”对象),我试图从中获取所有国家的所有 ESS 轮次。为了稍微有效地做到这一点,我正在尝试创建一个可以为我执行此操作的函数,但是我遇到了一些问题:首先,如果我使用“粘贴”函数来获取对象的名称,我会收到错误:
Error in paste: could not find function "paste<-"
. 其次,当尝试使用该函数设置名称只是为了查看它是否可以在没有粘贴部分的情况下工作时,它运行没有错误,但也没有任何结果。谁能看到解决方案?我感谢所有帮助!
ESS_Load <- function(N, CC){
temp <- Data[[N]]
paste(N, CC, sep = "_") <-
subset(temp, cntry == CC)
rm(temp)
}
ESS_Load(9, "NO")
解决方案
正如我从您的评论中了解到的那样,您希望创建一个{CC}_{N}
在调用环境中命名的数据框,作为函数的副作用。
这可以通过以下方式实现:
# first build sample data
set.seed(1)
Data <- list(iris[sample(nrow(iris),5),], iris[sample(nrow(iris),5),])
Data
#> [[1]]
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 68 5.8 2.7 4.1 1.0 versicolor
#> 129 6.4 2.8 5.6 2.1 virginica
#> 43 4.4 3.2 1.3 0.2 setosa
#> 14 4.3 3.0 1.1 0.1 setosa
#> 51 7.0 3.2 4.7 1.4 versicolor
#>
#> [[2]]
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 85 5.4 3.0 4.5 1.5 versicolor
#> 21 5.4 3.4 1.7 0.2 setosa
#> 106 7.6 3.0 6.6 2.1 virginica
#> 74 6.1 2.8 4.7 1.2 versicolor
#> 7 4.6 3.4 1.4 0.3 setosa
iris_Load <- function(N, CC){
nm <- paste(CC, N, sep = "_")
res <- subset(Data[[N]], Species == CC)
assign(nm, res, envir = parent.frame()) # create your object with right name and value in calling environment
invisible() # will return NULLL without printing
}
iris_Load(1, "setosa")
setosa_1
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 43 4.4 3.2 1.3 0.2 setosa
#> 14 4.3 3.0 1.1 0.1 setosa
如果您有能力执行以下操作,则可以说是更好的做法,但具有副作用的功能可能会令人惊讶,并且在大多数情况下通常不鼓励使用:
iris_Load <- function(N, CC){
subset(Data[[N]], Species == CC)
}
setosa_1 <- iris_Load(1, "setosa")
setosa_1
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 43 4.4 3.2 1.3 0.2 setosa
#> 14 4.3 3.0 1.1 0.1 setosa
```
推荐阅读
- git - 如何让 git worktree add 像示例一样工作?
- python - 使用 Pandas (df.style.applymap) 在 Pycharm 中设置表格样式?
- r - 从行中选择第 i 个最高值并分配给新列的最快方法
- bash - 在bash中计算平方根到小数位
- android - 在 python 服务器和 android(java) 客户端之间使用 grpc 创建连接
- javascript - Javascript - 从 JSON 数组返回一个 JSON 对象
- java - 在java中打印两个字符串变量时如何删除多余的空格
- rotation - 将旋转分解为围绕任意正交轴的旋转的更快方法
- python - 我需要找到用户输入数字列表的平均值并且某些东西不起作用
- javascript - Vue.js - 使用 JSX 语法访问子渲染函数中的父属性