简体   繁体   中英

How to delete first level of headers of a Dataframe in R?

I created a data frame from an aggregate - function. The length of the data-frame is two. However when I print the data-frame out 5 columns appear. How does R handle headers and sub headers in a data frame? How can I get rid of the first level of headers if this is the case here?

d <- data.frame("User id"=c(1,1,2,3,1),
                block=c("north","south","east","west","south"), check.names = F)

f <- function(l, vec) {
  vec[l] <- 1
  vec
}

vec <- setNames(rep(0, 4), levels(d$block))
df <- aggregate(block~`User id`, d, f, vec)

These are the outputs that confuse me:

>names(df)
[1] "User id" "block"



> df
  User id block.east block.north block.south block.west
1       1          0           1           1          0
2       2          1           0           0          0
3       3          0           0           0          1

This is what I want to have:

 > names(df)
 > "User id" "block.east" "block.north" "block.south" "block.west"

We can do this more easily with table

out <- as.data.frame.matrix(+(table(d) > 0))
names(df) <- paste0("block.", names(df))

Regarding the issue in OP's output, it is a matrix column,

str(df)
#'data.frame':  3 obs. of  2 variables:
# $ User id: num  1 2 3
# $ block  : num [1:3, 1:4] 0 1 0 1 0 0 1 0 0 0 ...
#   ..- attr(*, "dimnames")=List of 2
#  .. ..$ : NULL
#  .. ..$ : chr  "east" "north" "south" "west"

so we can convert to regular data.frame with

df <- do.call(data.frame, df)
names(df)
#[1] "User.id"     "block.east"  "block.north" "block.south" "block.west" 

str(df)
#'data.frame':  3 obs. of  5 variables:
# $ User.id    : num  1 2 3
# $ block.east : num  0 1 0
# $ block.north: num  1 0 0
# $ block.south: num  1 0 0
# $ block.west : num  0 0 1

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