简体   繁体   中英

loop over changing the default numeric rownames to texts in R

I am writing a loop to change the default numeric row names associated with a matrix (matrix x in my case) to text characters specified in one of the columns of an existing matrix (column with name “sdp” in matrix “temp”).So my loop looks like:

for ( i in 2008:2013) {

  temp = p[p$year == i,]

assign(sprintf("x_%d",i), data.matrix(temp[c("A", "B")]))

rownames(get(sprintf("x_%d",i)))= temp$sdp
}

However, I keep getting the following error message

> rownames(get(sprintf("x_%d",i)))=temp$sdp

Error in rownames(get(sprintf("x_%d", i))) = temp$sdp : 
  target of assignment expands to non-language object

These work:

> rownames(x_2008)=temp$sdp

> rownames(get(sprintf("x_%d",i)))

 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20" "21"
[22] "22" "23" "24" "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35" "36" "37" "38" "39" "40" "41" "42"
[43] "43" "44" "45" "46" "47" "48" "49" "50" "51" "52" "53" "54" "55"

> rownames(x_2008)

 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20" "21"
[22] "22" "23" "24" "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35" "36" "37" "38" "39" "40" "41" "42"
[43] "43" "44" "45" "46" "47" "48" "49" "50" "51" "52" "53" "54" "55"

It's never a good idea to use assign like that. You should probably be using a list like

xx <- lapply(split(p, p$year), function(x) {rownames(x)<-x$sdp; x[,-(1:2)]})

and then you would have

xx[["2008"]]

and so on for each year. The real problem with what you had was the attempted changing of the value with get when you need to update with assign . Here's a better working example

#sample data
p<-data.frame(year=rep(2008:2010, each=3), sdp=rep(letters[1:3], 3), 
    A=runif(9), B=runif(9))

for ( i in 2008:2010) {
  temp <- p[p$year == i,]
  X <- data.matrix(temp[c("A", "B")])
  rownames(X) <- temp$sdp
  assign(sprintf("x_%d",i), X)
}

But the use of assign/get is a sure sign you're not really doing things "The R Way"

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.

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