'R langugae : %in% promblem?
d1 <- data.frame("char"=c("a", "b", "c", "o", "m", "p"))
print("a" %in% d1)
I don't know why this code is "FALSE".
Solution 1:[1]
That returns false because d1 is a data frame - and a data frame is a list that contains columns. The %in% method as you've written it "a" %in% d1 is testing if the value "a" is a column of d1, which it is not.
You can use "a" %in% d1$char to look in a specific column. You could use "a" %in% unlist(d1) to look in all the columns. You can use "a" == d1 to compare a to every individual value in d1, and wrap that in any() as any("a" == d1) to also get a single TRUE result.
Things can get a little strange depending of if the data frame has multiple rows and if the vector you're testing has multiple values:
## 1 value in 1-row data frame works
"a" %in% data.frame(x = "a", y = "b")
# [1] TRUE
## With two values to test, we're still looking for individual columns
c("a", "b") %in% data.frame(x = c("a", "b"))
# [1] FALSE FALSE
## This is FALSE FALSE because there isn't a column that the whole
## column is "a", nor is there a column that the whole column is "b"
## Both "a" and "b" are whole columns here:
c("a", "b") %in% data.frame(x = "a", y = "b")
# [1] TRUE TRUE
## So we get TRUE TRUE
## Here's the way to test a whole column with more than 1 value:
list(c("a", "b")) %in% data.frame(x = c("a", "b"))
[1] TRUE
Solution 2:[2]
The statement inside your print() function is a logic test.
If you want to print the contents of your "char" column, you could try this:
d1 <- data.frame("char"=c("a", "b", "c", "o", "m", "p"))
print(d1$char)
Extra tips:
- You can change
"char"to justchar- the dataframe will still name your columnchar - you don't need to use
print()at all in this instance, just typed1$char
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Christian |
