Spread Function: "Error: `var` must evaluate to a single number or a column name.."

Good day,

Looking for some assistance as I am at my wit's end. I thought this was going to be so simple!

I have a dataset with which I'd like to do some crosstabulations in dplyr. I want to make a table with Gender for rows, dxyear for columns and the total for each. Based on what I found online, I made the following code:

x <- Surv%>% 
  group_by(Surv$dxyear,Surv$Gender)%>% 
  summarise(n=n())%>% 
  spread(Surv$dxyear,n)

I got the error message:
Error: var must evaluate to a single number or a column name, not a double vector

I tried replacing the spread function with pivot_wider:
pivot_wider(names_from=Surv$dxyear,values_from,n)
which resulted in the error message:
Error: Unknown columns 2012, 1997, 2008, 2008, 2008``

I tried converting Surv$dxyear to a character variable, but it didn't make a difference. Also, as for the spread function error, I've googled it for two days, but no one seems to explain what it actually means and their solutions don't look much different than my code (or aren't relevant). Any assistance would be greatly appreciated!

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

One issue I see in your code is that you userSurv$dxyear to refer to variables. In general with tidyverse function, you never need to do this -- you can just use the bare column names like dxyear. Is this what you're looking for?

library(tidyverse)

df <- tribble(
  ~CaseID, ~dxyear, ~Gender,
  41218,   2012,   "Male",
  41219,   1997, "Female",
  41220,   2008, "Female",
  41221,   2008,   "Male",
  41222,   2008,   "Male",
  41223,   2010, "Female",
  41224,   2005, "Female",
  41225,   2000,   "Male",
  41226,   1993, "Female",
  41227,   2001,   "Male"
 )

df %>% 
  count(dxyear, Gender) %>% 
  pivot_wider(names_from = dxyear, values_from = n)
#> # A tibble: 2 x 9
#>   Gender `1993` `1997` `2000` `2001` `2005` `2008` `2010` `2012`
#>   <chr>   <int>  <int>  <int>  <int>  <int>  <int>  <int>  <int>
#> 1 Female      1      1     NA     NA      1      1      1     NA
#> 2 Male       NA     NA      1      1     NA      2     NA      1

Created on 2020-06-09 by the reprex package (v0.3.0)

Wow, thanks so much! It indeed worked (sorry I deleted the dataframe. I forgot about the Datapasta thing and tried to do it, but you answered before I could!). Thanks so much!

1 Like

Glad you got it working! Would you mind marking the solution so others having the same problem can find it?

No problem. Thanks again!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.