简体   繁体   English

新的 dataframe 来自旧的 dataframe 与公式

[英]New dataframe from old dataframe with formula

I have this dataframe:我有这个 dataframe:

a<-c(1,2,3)
b<-c(2,1,2)
c<-c(3,1,1)
test<-data.frame(a,b,c)
test
  a b c
1 1 2 3
2 2 1 1
3 3 2 1

is there a way that i can create a new dataframe using a string vector like:有没有一种方法可以使用如下字符串向量创建一个新的 dataframe:

formul<-c("2*a0+b0","2*b0+3*c0")

where "a0" is the first column, "b0" the second and so on, that gives me as result:其中“a0”是第一列,“b0”是第二列,依此类推,结果如下:

test2
  2a0+b0 2b0+3c0
1   4      13
2   5      5
3   8      7

i tried with: test2<-cbind(2*test$a+test$b,2*test$b+3*test$c) but couldnt came up with how to convert formul vector yet我试过: test2<-cbind(2*test$a+test$b,2*test$b+3*test$c)但还没有想出如何转换公式向量

An option would be to loop over the 'formul', remove the '0's from the string (as it needs to match the column names of the 'test' data) with gsub , then use with to eval utate the string within the env of the 'test' data一个选项是循环遍历“公式”,使用gsub从字符串中删除“0”(因为它需要匹配“测试”数据的列名),然后使用with eval环境中的字符串“测试”数据

sapply(formul, function(x) with(test, eval(parse(text = gsub('0', '', x)))))
#      2*a0+b0 2*b0+3*c0
#[1,]       4        13
#[2,]       5         5
#[3,]       8         7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM