[R] Reading then transposing from file

Berend Hasselman bhh at xs4all.nl
Sat Mar 17 14:28:58 CET 2012


On 17-03-2012, at 10:27, diond wrote:

> Hi,
> 
> I'm an R beginner and I'm struggling with what should be a rudimentary task.
> 
> My data is along these lines:
> 
> ID name1 name2 name3 name4
> Class 0 1 0 2
> Var1 A B C A
> Var2 B C C A
> Var3 C A B A
> 
> etc.
> 
> I'm using the following:
> 
> foo <- data.frame(t(read.table("file", header=FALSE)))
> 
> but of course now it's not using ID, Class, etc. as column names.
> 
> As you can imagine, I'd like to be able to use, say, foo$Var2 or foo$ID.
> 
> What's the best way to achieve this?

I found this on Stackoverflow http://stackoverflow.com/questions/6778908/r-transposing-a-data-frame

and tried

ftext <- "ID name1 name2 name3 name4
Class 0 1 0 2
Var1 A B C A
Var2 B C C A
Var3 C A B A"

df.1 <- read.table(text=ftext, header=FALSE, stringsAsFactors=FALSE)
df.1
str(df.1)

df.names <- df.1[,1]
df.3 <- as.data.frame(t(df.1[,-1]), stringsAsFactors=FALSE)
colnames(df.3) <- df.names
rownames(df.3) <- NULL

# and maybe
df.3[,"Class"] <- as.numeric(df.3[,"Class"])
df.3 

str(df.3) # Check the column types

Berend



More information about the R-help mailing list