0

So, with ths dummy dataset

test_species <- c("a", "b", "c", "d", "e")
test_abundance <- c(4, 7, 15, 2, 9)
df <- rbind(test_species, test_abundance)
df <- as.data.frame(df)
colnames(df) <- c("a", "b", "c", "d", "e")
df <- dplyr::slice(df, 2)

we get a dataframe that's something like this:

a     b     c     d     e    
4     7     15    2     9 

I'd like to transform it into something like

species      abundance
a            4
b            7
c            15
d            2
e            9

using the reshape2 function melt(). I tried the code

melted_df <- melt(df,
              variable.name = "species", 
              value.name = "abundance")

but that tells me: "Using a, b, c, d, e as id variables", and the end result looks like this:

a     b     c     d     e    
4     7     15    2     9 

What am I doing wrong, and how can I fix it?

Tino
  • 2,091
  • 13
  • 15
Snowfaerie
  • 23
  • 1
  • 10
  • I don't know `reshape2`, but if you just want to get the result, use `tidyr::gather(df, "species", "abundance")` – Tino Sep 13 '18 at 12:24
  • with reshape2 you should be able to force this by giving the measure.vars parameter. melt(df, measure.vars = names(df)) – TinglTanglBob Sep 13 '18 at 12:26

2 Answers2

2

You can define it in the correct shape from the start, using only base library functions:

> data.frame(species=test_species, abundance=test_abundance)
  species abundance
1       a         4
2       b         7
3       c        15
4       d         2
5       e         9
Benjamin
  • 11,560
  • 13
  • 70
  • 119
-1

Rbind is adding some odd behaviour I think, I cannot explain why.

A fairly basic fix is:

test_species <-c("a", "b", "c", "d", "e")
test_abundance <- c(4, 7, 15, 2, 9)
df <- data.frame(test_species, test_abundance) #skip rbind and go straight to df
colnames(df) <- c('species', 'abundance') #colnames correct

This skips the rbind function and will give desired outcome.

A.Fowler
  • 81
  • 7
  • 1
    The "odd" behaviour of `rbind()` is easily explained. `rbind()` creates a *matrix* from the given vectors, and as all elements of a matrix do have the same type, all matrix elements are coerced to character. For details, please, see `help("rbind")`. – Uwe Sep 18 '18 at 05:59
  • Thanks, very helpful – A.Fowler Sep 19 '18 at 07:10