locket
locket

Reputation: 761

R converting a vector to a dataframe with one row

I have a vector a<-c(0, 0). I want to convert this to a dataframe and then remove duplicated rows (as part of a loop).

This is my code:

a<-c(0, 0)
df<-t(as.data.frame(a))
distinct(df)

This isn't working because df isn't a dataframe even though I have converted it to a dataframe in the second step. I'm not sure how to make this work when the dataframe only has one row.

Upvotes: 0

Views: 1365

Answers (4)

PaulS
PaulS

Reputation: 25528

Using dplyr and matrix:

library(dplyr)

data.frame(matrix(0, 1, 2)) %>% 
  distinct

#>   X1 X2
#> 1  0  0

Upvotes: 0

B. Christian Kamgang
B. Christian Kamgang

Reputation: 6529

You can use rbind.data.frame function as follows:

a <- c(0,0)
df = rbind.data.frame(a)
distinct(df)

Upvotes: 0

koolmees
koolmees

Reputation: 2783

The function t will transform the data.frame back to a matrix. The simplest solution would be to simply change the order of the functions:

a <- c(0,0)
df <- as.data.frame(t(a))
distinct(df)

Upvotes: 1

Quinten
Quinten

Reputation: 41553

swap t and as.data.frame like this:

library(dplyr)
a<-c(0, 0)
df<-as.data.frame(t(a))
distinct(df)

Output:

  V1 V2
1  0  0

Upvotes: 5

Related Questions