[R] Simple Stacking of Two Columns

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Tue Apr 4 14:20:36 CEST 2023


Just to repeat:
you have

   NamesWide<-data.frame(Name1=c("Tom","Dick"),Name2=c("Larry","Curly"))

and you want

   NamesLong<-data.frame(Names=c("Tom","Dick","Larry","Curly"))

There must be something I am missing, because

   NamesLong <- data.frame(Names = c(NamesWide$Name1, NamesWide$Name2))

appears to do the job in the simplest possible manner.  There are all sorts
of alternatives, such as
   data.frame(Name = as.vector(as.matrix(NamesWide[, 1:2])))

As for stack(), the main problem there was a typo (Names2 for Name2).

> stack(NamesWide)
  values   ind
1    Tom Name1
2   Dick Name1
3  Larry Name2
4  Curly Name2

If there were multiple columns, you might do

> stack(NamesWide[,c("Name1","Name2")])$values
[1] "Tom"   "Dick"  "Larry" "Curly"


On Tue, 4 Apr 2023 at 03:09, Sparks, John <jspark4 using uic.edu> wrote:

> Hi R-Helpers,
>
> Sorry to bother you, but I have a simple task that I can't figure out how
> to do.
>
> For example, I have some names in two columns
>
> NamesWide<-data.frame(Name1=c("Tom","Dick"),Name2=c("Larry","Curly"))
>
> and I simply want to get a single column
> NamesLong<-data.frame(Names=c("Tom","Dick","Larry","Curly"))
> > NamesLong
>   Names
> 1   Tom
> 2  Dick
> 3 Larry
> 4 Curly
>
>
> Stack produces an error
> NamesLong<-stack(NamesWide$Name1,NamesWide$Names2)
> Error in if (drop) { : argument is of length zero
>
> So does bind_rows
> > NamesLong<-dplyr::bind_rows(NamesWide$Name1,NamesWide$Name2)
> Error in `dplyr::bind_rows()`:
> ! Argument 1 must be a data frame or a named atomic vector.
> Run `rlang::last_error()` to see where the error occurred.
>
> I tried making separate dataframes to get around the error in bind_rows
> but it puts the data in two different columns
> Name1<-data.frame(c("Tom","Dick"))
> Name2<-data.frame(c("Larry","Curly"))
> NamesLong<-dplyr::bind_rows(Name1,Name2)
> > NamesLong
>   c..Tom....Dick.. c..Larry....Curly..
> 1              Tom                <NA>
> 2             Dick                <NA>
> 3             <NA>               Larry
> 4             <NA>               Curly
>
> gather makes no change to the data
> NamesLong<-gather(NamesWide,Name1,Name2)
> > NamesLong
>   Name1 Name2
> 1   Tom Larry
> 2  Dick Curly
>
>
> Please help me solve what should be a very simple problem.
>
> Thanks,
> John Sparks
>
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list