1

I generally try to avoid code duplication, even in single rows. However, I find myself writing lines like this in R a lot:

# R code
my_long_vector_var_name <- append(my_long_vector_var_name, new_var)
my_long_int_name <- my_long_int_name + 1

In Python, not only are there way less letters in a row - I also do not have to write the same variable twice, which potentially reduces errors:

my_long_vector_var_name.append(new_var)
my_long_int_name += 1

For the second one, this question indicates that there truely is no comparable "short" way in R. The question, however, is more than 6 years old. Is there still no better way to do this in R?

Thomas
  • 4,696
  • 5
  • 36
  • 71
  • I don't think there are shortcuts, no. Generally, R objects are immutable and copied when modified, one has to explicitly overwrite the original variable by assigning the copy. – Axeman Jan 26 '18 at 12:57
  • 4
    If you grow vectors often, you are doing it wrong. – Roland Jan 26 '18 at 13:03
  • @Roland: I mainly do it for data cleaning: "If the table contains a certain element, add it to the processing vector..." "If I use realtime data, add this column to the list of factors...". I don't actually grow any data frames / vectors of data ;-) – Thomas Jan 26 '18 at 13:49

2 Answers2

2

magrittr has a %<>% operator which pipes and updates an object.

library('magrittr')

v <- c(1, 2)

v %<>% append(3)
v
#> [1] 1 2 3

v %<>% add(1)
v
#> [1] 2 3 4
Paul
  • 8,734
  • 1
  • 26
  • 36
  • While I like the Python dot notation (v.append(3)) better, this seems to be exactly what I was looking for in R. – Thomas Jan 26 '18 at 13:53
1

for the first question to some extend you can use %>% operator from dplyr package

library(dplyr)
my_long_vector<-rep(c("A","B","C"),10)%>%c("NEW VALUE")
Antonios
  • 1,919
  • 1
  • 11
  • 18
  • 3
    While `dplyr` uses the pipe, it is from the `magrittr` package, which has a more appropriate operator (see Paul's answer) – Axeman Jan 26 '18 at 13:06