I'm quite new to R and failed to google the answer. The question is, how can I tell R to treat a character string value as a part of code, in a manner SAS resolve() function does?
Say, I have a data frame containing numeric columns V1, ..., Vn and exactly n rows. I wish to sum up all the 'diagonal' elements V = V1[1] + V2[2]... + Vn[n] but n is large enough for manual summation (below, n=2 for simplicity).
I'm trying to put the strings "dat$V1[1]", "dat$V2[2]" in a character C and then extract the corresponding numerical value (all in a loop step):
> dat <- data.frame(V1 = c(2,3), V2 = c(7,11))
> dat
V1 V2
1 2 7
2 3 11
V = 0
for(i in 1:nrow(dat))
{
C = paste('dat$V',format(i,trim=TRUE),'[',format(i,trim=TRUE),']',
sep="" )
f = Xfun(C)
V = V + f
}
What should be used instead of Xfun? I've tried as.formula(), asOneSidedFormula(), get("...") and some other, but it's essential that dat$V1 is not an object:
> exists("dat")
[1] TRUE
> exists("dat$V1")
[1] FALSE
Your help is much appreciated.
If you just want to sum the diagonal elements of a square matrix, just do
dat <- data.frame(V1 = c(2,3), V2 = c(7,11))
sum(diag(as.matrix(dat)))
If you want to evaluate a text string in R, read up a bit on eval or do ? eavl
? eavl
in R.
For your problem, you can do this:
dat <- data.frame(V1 = c(2,3), V2 = c(7,11))
dat
V = 0
for(i in 1:nrow(dat))
{
C = paste('dat$V',format(i,trim=TRUE),'[',format(i,trim=TRUE),']',
sep="" )
f = eval(parse(text=C))
V = V + f
}
To finalize:
a) correct answer using text parsing and evaluation
V = 0
for(i in 1:nrow(dat))
{ C = paste('dat$V',as.character(i),'[',as.character(i),']',
sep='' )
V = V + eval(parse(text=C))
}
b) correct action ESPECIALLY for a data frame - without requiring text evaluation but addressing data frame columns directly by name
V = 0
for(i in 1:nrow(dat))
{ col = paste('V',as.character(i),
sep='')
V = V + dat[i,col]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.