Wolfram Fischer
2004-Dec-07 08:47 UTC
[R] how to test the existence of a name in a dataframe
I wanted to test if there exists already a name (which is incidentally a substring of another name) in a dataframe. I did e.g.:> data(swiss) > names(swiss)[1] "Fertility" "Agriculture" "Examination" "Education" [5] "Catholic" "Infant.Mortality"> ! is.null(swiss$EduX)[1] FALSE> ! is.null(swiss$Edu)[1] TRUE I did not expect to get TRUE here because ``Edu'' does not exist as name of ``swiss''. I did finally:> 'Edu' %in% names(swiss)for which I got the expected FALSE. My question: What is the recommended way to do such a test? Thanks - Wolfram Fischer
Dimitris Rizopoulos
2004-Dec-07 09:06 UTC
[R] how to test the existence of a name in a dataframe
Hi Wolfram, this behaviour is due to partial matching. Observe that data(swiss) swiss$Ed swiss$Edu swiss$Educ I think the best way to do it is with `%in%' or `match()', i.e., c("Ed", "Edu", "Educ", "Education") %in% names(swiss) I hope it helps. Best, Dimitris ---- Dimitris Rizopoulos Ph.D. Student Biostatistical Centre School of Public Health Catholic University of Leuven Address: Kapucijnenvoer 35, Leuven, Belgium Tel: +32/16/336899 Fax: +32/16/337015 Web: http://www.med.kuleuven.ac.be/biostat http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm ----- Original Message ----- From: "Wolfram Fischer" <wolfram at fischer-zim.ch> To: <r-help at stat.math.ethz.ch> Sent: Tuesday, December 07, 2004 9:47 AM Subject: [R] how to test the existence of a name in a dataframe>I wanted to test if there exists already a name (which is > incidentally a substring of another name) in a dataframe. > I did e.g.: > >> data(swiss) >> names(swiss) > [1] "Fertility" "Agriculture" "Examination" > "Education" > [5] "Catholic" "Infant.Mortality" > >> ! is.null(swiss$EduX) > [1] FALSE > >> ! is.null(swiss$Edu) > [1] TRUE > > I did not expect to get TRUE here because ``Edu'' does not exist > as name of ``swiss''. > > I did finally: >> 'Edu' %in% names(swiss) > for which I got the expected FALSE. > > My question: What is the recommended way to do such a test? > > Thanks - Wolfram Fischer > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! > http://www.R-project.org/posting-guide.html >