Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在for循环的dataframe中创建变量?_R_Variables_For Loop - Fatal编程技术网

如何在for循环的dataframe中创建变量?

如何在for循环的dataframe中创建变量?,r,variables,for-loop,R,Variables,For Loop,我有一个名为mydata的R数据框,其中包含了特定年龄和特定身高的人数。因此,在数据框架中,我有变量mydata$ageto10(=十岁以下的人数),mydata$ageto20(=二十岁以下的人数),以此类推,年龄分别为35岁、42岁和65岁。高度(和其他几个变量)也是如此 我想创建一个新的变量,它涉及到10到25岁、25到35岁、35到42岁和42到65岁之间的人数。对于第一种情况,我想做: mydata$age10to25 <- mydata$ageto25 - mydata$age

我有一个名为mydata的R数据框,其中包含了特定年龄和特定身高的人数。因此,在数据框架中,我有变量
mydata$ageto10
(=十岁以下的人数),
mydata$ageto20
(=二十岁以下的人数),以此类推,年龄分别为35岁、42岁和65岁。高度(和其他几个变量)也是如此

我想创建一个新的变量,它涉及到10到25岁、25到35岁、35到42岁和42到65岁之间的人数。对于第一种情况,我想做:

mydata$age10to25 <- mydata$ageto25 - mydata$ageto10

mydata$age10至25我猜您是来自另一个统计数据包(
stata
可能或
SAS
)的难民。不能使用“指定”来使用
$
粘贴来指定列。一般来说,如果您使用
assign
执行标准任务,那么您所做的不是惯用的
R
,或者有更好的解决方案

差不多

lower <- c(10,25,35,42)
upper <- c(25,35,42,65)

# create the differences
newData <-   myData[,paste0('ageto',upper)] - myData[, paste0('ageto',lower)]
# name them with valid names (not starting with numbers
names(newData) <- paste0('from',lower,'to',upper)
# add as columns to the original
myData <- cbind(myData, newData)

没门,太棒了!谢谢(注:是的,来自斯塔塔的难民;-)我每天都越来越爱R)@user1780218如果这解决了你的问题,你应该给答案打勾!
lower <- c(10,25,35,42)
upper <- c(25,35,42,65)

# create the differences
newData <-   myData[,paste0('ageto',upper)] - myData[, paste0('ageto',lower)]
# name them with valid names (not starting with numbers
names(newData) <- paste0('from',lower,'to',upper)
# add as columns to the original
myData <- cbind(myData, newData)