Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

properly labeled headers in R using subset

I am attempting to use subset to send a row matching a specific value from a column, but I'm having issues recognizing a specific header I have defined and not another.

foo.csv is:

    ,3ZSJ_ALA_A_142,ED
    1,0,0.249
    2,10,0.379
    3,20,0.542

example r code:

    T1 = read.csv('foo.csv', header=T)
    foo <- subset(T1, 3ZSJ_ALA_A_142 == '10')
    Error: unexpected symbol in "foo <- subset(T1, 3ZSJ_ALA_A_142"
    Execution halted

I have also tried to put the 3ZSJ_ALA_A_142 in parentheses and then my output lis is inappropriate, it should give the row with 10, but it gives this:

    [1] X               X3ZSJ_ALA_A_142 ED  
    <0 rows> (or 0-length row.names)

If I do ED instead of 3ZSJ_ALA_A_142 in my r code I get this lis:

      X X3ZSJ_ALA_A_142    ED 
    2 2              10 0.379

Am I using an inappropriate function, or is my syntax all mucked up? any points would be greatly appreicated, thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Names starting with numbers such as 3ZSJ_ALA_A_142 are not syntactically valid.

When you call read.csv it has an argument check.names which will check the names for syntactic validity, and adjust if necessary (the default is check.names = TRUE)

If you are using this to convert to syntactically valid names, then it will (usually) append an X at the beginning of names starting with numerals

so the following should work.

foo <- subset(T1, X3ZSJ_ALA_A_142 == '10')

If you don't want to convert the names, then use check.names = FALSE and use backticks eg ` to refer to the non-syntactic names.

 T2 = read.csv('foo.csv', header=TRUE, check.names = FALSE )
    foo <- subset(T1, `3ZSJ_ALA_A_142` == '10')

Beware using non-syntactic names as some functions may not deal appropriately with them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...