1

I'm trying to fill in a dataframe column with character strings pulled from a second dataframe. When I try to do this, however, the new entries in the column turn into lists:

for (i in nyc_districts$SUBWAY_STOP){
  nyc_districts$SUBWAY_STOP[i]<-substops$V3[[i]]
}

class(substops$V3[[1]])
[1] "character"

class(nyc_districts$SUBWAY_STOP[1])
[1] "list"

What is going on? How can I turn the new entries into strings? Many thanks!

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Traviskorte
  • 113
  • 8
  • Welcome to Stack Overflow! Please add reproducible sample for good people here to help you. See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – CHP Mar 14 '13 at 01:23

1 Answers1

3

You are getting confused by [ and [[ for indexing.

To quote from the help

Recursive (list-like) objects

Indexing by [ is similar to atomic vectors and selects a list of the specified element(s).

Both [[ and $ select a single element of the list.

Hence the difference

x <- list(a = 1:4, b= 1:2)
class(x[1])
## [1] "list"
 class(x[[1]])
## [1] "integer"

Without knowing what your data looks like I can't suggest a better approach to your exact problem except to say that there will be a better way.

mnel
  • 113,303
  • 27
  • 265
  • 254
  • Thanks mnel. To clarify, what I'm looking for is a way to prevent the column entries from being lists at all. (I'm ultimately trying to export to a shapefile, and the fact that the entries are lists is generating the error "data frame contains columns of unsupported class “list”") – Traviskorte Mar 14 '13 at 01:23
  • @user2167839 - edit your question to include a reproducible example, at the moment `for(i in nyc_districts$SUBWAY_STOP){nyc_districts$SUBWAY_STOP[i]...` is not doing what you think it is. perhaps you want `for( i in seq_along( nyc_districts$SUBWAY_STOP)){...` – mnel Mar 14 '13 at 01:32