Concatenate rows of a data frame

前端 未结 4 1484
醉梦人生
醉梦人生 2020-11-30 07:28

I would like to take a data frame with characters and numbers, and concatenate all of the elements of the each row into a single string, which would be stored as a single el

4条回答
  •  一整个雨季
    2020-11-30 07:55

    This is indeed a little weird, but this is also what is supposed to happen. When you create the data.frame as you did, column letters is stored as factor. Naturally factors have no ordering, therefore when as.numeric() is applied to a factor it returns the ordering of of the factor. For example:

    > df[, 1]
    [1] A B C D E
    Levels: A B C D E
    > as.numeric(df[, 1])
    [1] 1 2 3 4 5
    

    A is the first level of the factor df[, 1] therefore A gets converted to the value 1, when as.numeric is applied. This is what happens when you call paste(df[1, ]). Since columns 1 and 2 are of different class, paste first transforms both elements of row 1 to numeric then to characters.

    When you want to concatenate both columns, you first need to transform the first row to character:

    df[, 1] <- as.character(df[, 1])
    paste(df[1,], collapse = "")
    

    As @sebastian-c pointed out, you can also use stringsAsFactors = FALSE in the creation of the data.frame, then you can omit the as.character() step.

提交回复
热议问题