[英]Creating new data frame in function in R
I've been trying to write a function which creates new object based on the previous one (after few changes). 我一直在尝试编写一个函数,该函数根据上一个对象(经过几次更改)创建新对象。 However, I didn't manage to do it. 但是,我没有做到这一点。 Here's my data frame: 这是我的数据框:
Names <- c("Tom", "Alex", "James", "John", "Wayne", "Harry")
a <- c(1,3,6,8, NA, 5)
b <- c(3,6,9,1, NA,1)
c <- c(7,3,1,6,NA,6)
d <- c(1,4,7,2,NA,8)
data <- data.frame(Names,a,b,c,d)
And here's my function 这是我的功能
NAvalues <- function(x,object, y){
object[sample(seq_len(nrow(object)), x, replace = FALSE),-1] <- NA
summary(object)
y <- data.frame(object)
}
The first part works fine, but I'm struggling to create a new object, which would have a name specified by y. 第一部分工作正常,但是我正在努力创建一个新对象,该对象的名称由y指定。
NAvalues(2, data, new)
When I use this, I get an error that there is no such an object as new
. 使用此方法时,出现一个错误,即没有new
这样的对象。 Can someone tell me why is it so? 有人可以告诉我为什么吗?
From what I understood, the objective of your task is to create a data.frame named as defined by the argument y
by executing the function NAvalues()
. 据我了解,您的任务目标是通过执行功能NAvalues()
创建一个由参数y
定义的NAvalues()
。
NAvalues <- function(x,object, y){
object[sample(seq_len(nrow(object)), x, replace = FALSE),-1] <- NA
summary(object)
assign(paste(y), data.frame(object), envir = .GlobalEnv)
}
NAvalues(x = 2, object = data, y = "new") #y must be a character because it is the name of the new data.frame
The key of the solution is 解决方案的关键是
assign(paste(y), data.frame(object), envir = .GlobalEnv)
which allows to create a variable named as the string
parameter
y
and assign that variable to the global.environment
这允许创建一个名为string
parameter
y
变量,并将该变量分配给global.environment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.