[R] Why is my data always imported as a list?

Sarah Goslee sarah.goslee at gmail.com
Mon Jun 11 18:41:36 CEST 2012


Hi,

Have you tried
str(CB_un)
to make sure the structure of your data is what you expect?

Does
boxplot(CB_un[, "Value"]~CB_un[, "State.Fips"])
work?

Look at this:
> testdf <- data.frame(a=1:3, b=11:13)
> class(testdf["a"])
[1] "data.frame"
> class(testdf[["a"]])
[1] "integer"
> class(testdf[, "a"])
[1] "integer"


A data frame is a special form of list, so the usual list subsetting
rules apply. Extracting a named component of a data frame with single
square brackets gives you a data frame. Using row, column notation or
double brackets gives a vector.

?"["
will give you more detail.

You have to use a data frame, and thus a list, for your data, since
you can't mix factor and numeric data types in a matrix.

Sarah

On Mon, Jun 11, 2012 at 12:29 PM, Samantha Sifleet
<Sifleet.Samantha at epamail.epa.gov> wrote:
> Hi,
>
> I am a relatively new to R. So, this is probably a really basic issue that
> I keep hitting.
>
> I read my data into R using the read.csv command:
>
> x = rep("numeric", 3)
> CB_un=read.csv("Corn_Belt_unirr.csv", header=TRUE, colClasses=c("factor",
> x))
>
> # I have clearly told R that I have one factor variable and 3 numeric
> variables in this table.
> #but if I try to do anything with them, I get an error
>
> boxplot(CB_un["Value"]~CB_un["State.Fips"])
>
> Error in model.frame.default(formula = CB_un["Value"] ~
> CB_un["State.Fips"]) :
>  invalid type (list) for variable 'CB_un["Value"]'
>
> # Because  these variables are all stored as lists.
> #So, I have to unpack them.
>
> CB_unirr_rent<-as.numeric(unlist(CB_un["Value"]))
> CB_unirr_State<-as.factor(unlist(CB_un["State.Fips"]))
>
> #before I can do anything with them
>
> boxplot(CB_unirr_rent~CB_unirr_State)
>
> Is there a reason my data is always imported as lists?  Is there a way to
> skip this upacking step?
>
> Thanks,
>
> Sam

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list