简体   繁体   中英

Why is expand.grid in R returning <0 rows>?

I'm trying to use expand.grid to eventually plot estimates from a statistical model. But the output is:

[1] ID     Age    Sex    Tcoded
<0 rows> (or 0-length row.names)

code:

new_df <- with(test,
               expand.grid(ID = factor(levels(ID)[1], levels = levels(ID)),
                           Age = gratia::seq_min_max(Age, n = 100),
                           Sex = factor(levels(Sex), levels = levels(Sex)),
                           Tcoded = median(Tcoded)))

If I remove the first line for ID , the function works. Why is this happening?

Try running each individual part of your problem to see what is happening

with(test,
  factor(levels(ID)[1], levels = levels(ID)))

returns

factor(0)
Levels: 

so has zero length and ruins everything else (because if any element of expland.grid has length zero the output data.frame has zero rows). You are trying to get the first level of ID before converting it to a factor. Don't know if you just wanted the first ID? or the ID just as levels instead of as numeric?

Simply convert ID from integer to a factor. By the way, you do not need an external package for the Age range calculation since base R's seq() can work.

test$ID <- as.factor(test$ID)

new_df <- with(
    test,
    expand.grid(ID = factor(levels(ID)[1], levels = levels(ID)),
                Age = seq(from=min(Age), to=max(Age), length.out=100),
                Sex = factor(levels(Sex), levels = levels(Sex)),
                Tcoded = median(Tcoded)
    )
)

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