1

I have a dataframe file, but instead of writing in column, it has been written in row, as below:

a: 1
b: 2
c: 3
a:3
b:2
c:9  
a: 4
b: 4
...

Now I want to read this file to a dataframe in R, so I will have a dataframe with three columns a, b and c, and the values as in the file.

How can I do that?

Thank you very much

jogo
  • 12,469
  • 11
  • 37
  • 42
Yang Mei Lian
  • 75
  • 1
  • 11

2 Answers2

1

Check:

> dt <- read.table("yourFile.anyFormat", header = F, sep = ":")
> dt
  V1 V2
1  a  1
2  b  2
3  c  3
4  a  3
5  b  2
6  c  9
7  a  4
8  b  4
9  c  4

Then select a,b,c:

> a <- dt[dt$V1 == 'a',]$V2
> b <- dt[dt$V1 == 'b',]$V2
> c <- dt[dt$V1 == 'c',]$V2

Fetch result:

> df <- data.frame(a,b,c)
> df
  a b c
1 1 2 3
2 3 2 9
3 4 4 4
xtluo
  • 1,961
  • 18
  • 26
  • It looks good, but it seems that I have to select ``a,b,c`` manually. Might be not work well if I have 1000 variables (1000 columns in the final dataframe). Is there an automatic way? – Yang Mei Lian Nov 11 '16 at 09:49
  • A proper solution may be encapsulate above code as a function for your specific use, which takes `yourFile` as an input parameter and returns with a `data.frame`. – xtluo Nov 11 '16 at 09:56
-1

In R, a dataframe is not a file. For your question,

df <- as.data.frame(matrix(c(
1,2,3,3,2,9,4,4,8), nrow=3, byrow=TRUE))
names(df) <- c("a","b","c")
df

#  a b c
#1 1 2 3
#2 3 2 9
#3 4 4 8

Other than that, perhaps, best way to pass data to R via Excel:

For example, in the mydata.xlsx file below,

. A B C
1 a b c
2 1 2 3
3 3 2 9
4 4 4 8

library(readxl)
mydata <- read_excel("C://Users//User//Documents//Revolution//mydata.xlsx")
mydata <- as.data.frame(mydata) 
Erdogan CEVHER
  • 1,788
  • 1
  • 21
  • 40
  • The answer is helpful for starters. Why for "-1" vote? – Erdogan CEVHER Nov 11 '16 at 09:31
  • Maybe because you are creating df from scratch, whereas OP is reading in the file, and resulting dataframe has 1 column, which then needs to be converted to 3 columns based on delimiter ":" and first column. This type of question asked many times before, I closed it as duplicate "reshape from long to wide". – zx8754 Nov 11 '16 at 10:03