0

Basic question but I'm a beginner sorry :-) And I still struggle with all these different data types etc. So I have a table with different variable names in column 1. In column 2 These variables have certain values. I want to extract now the value for a certain variable.

VarNames<-read.table(paste("O:/Daten/RatsDaten/CodesandDescription/VarNamesDir.asc"), sep="", skip=0,header=FALSE)

And the table Looks somehow like this

Test1      5
Test2      7
Test3      1

So how do I Access these Test variable values with their names? VarNames["Test1",2] didn't work..neither did any other option I've tried. Are there better data type options for this or how would I do it with a comfortable data frame?

4

2 回答 2

3

你应该有这两种情况之一,要么

Testxx 是 VarNames 的行名,您可以使用 rownames(VarNames) 对其进行测试,在这种情况下,您应该这样做:

    VarNames["Test1",1]    

或者 Testxx 是列的组成部分,你应该这样做:

    VarNames[VarNames$v =='Test1',2]

对于第一个选项:

m <- matrix(1:3,ncol=1,dimnames=list(paste0('Test',1:3),NULL))
m['Test1',]
Test1 
    1 

对于第二个选项

m1 <- data.frame(v=paste0('Test',1:3),b=1:3)
m1[m1$v=='Test1',]
      v b
1 Test1 1
于 2013-07-03T07:54:16.287 回答
0

由于您的示例不可重现,因此不清楚第一列是表示行名还是带有值 TestX 的变量。

如果它是一个变量,您的表实际上如下所示:

V1         V2
Test1      5
Test2      7
Test3      1

因此,您可以Test2通过调用VarNames[VarNames$V1 == "Test2",]整行或VarNames[VarNames$V1 == "Test2",2]仅获取值来获取值。您指定 2 因为它是第二列。

如果第一列表示行名,则调用是VarNames["Test2",]针对整行的,或者如@agstudy 回答的那样,VarNames["Test2",1]仅针对值。您指定 1 因为它是提供的第一列Test2是行名,因此不包含在列中。

于 2013-07-03T08:00:45.533 回答