I have a small dataframe as below.
sad <- structure(list(a = c(1, 2), b = c(3, 4)), class = "data.frame", row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"))
Can anyone please help me as to what is the below operation doing?
sad[, a := sad[, "Ma"] == "Y"]
# A tibble: 2 x 2
a b
<dbl> <dbl>
1 1 3
2 2 4
When I execute the above operation, i get the same output, but not sure what is the intent here. Can anyone help me?
CodePudding user response:
Update: After some research I found this: What are the differences between "=" and "<-" assignment operators in R?
The answer by @Konrad Rudolf discusses the difference between =
and <-
and interestingly using <-
instead of =
will throw an error:
# in contrast to sad[, a = anything_here]
sad[, a <- anything_here]
error: Error in `[.tbl_df`(sad, , a <- anything) : object 'anything' not found`
also in your example if you use <-
sad[, a <- sad[, "Ma"] == "Y"]
And to conclude also from the mentioned site answer by @Nosredna discusses:
"Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice."
So all in all maybe it is an assignement issue.
First answer:
Let's consider this: Breaking down what you have on the right side from the comma in closed brackets which operates on columns. On the other side the left side from comma would operate on rows:
And also consider as @Onyambu noted in the comments:
Note that sad
is a tibble eg sad[, a = anything_here]
will still produce a result. No error thrown
# will not work no column a (a is a object)
sad[, a]
# All rows and the column named "a" -> this will work
sad[, 'a']
# will not work because you want to get all rows and column "Ma" -> there is no colum Ma in sad
sad[, "Ma"]
# here you assign nothing to object a
a = sad[, "Ma"]
# consecutevily you compare a = sad[, "Ma"] (e.g. nothing) to string 'Y'
# will not work because 'Ma' column don't exist.
sad[, "Ma"] == "Y"