I need a bit of help with jargon, and a short piece of example code. Different types of objects have a specific way of outputting themselves when you type the name of the object and hit enter, an lm object shows a summary of the model, a vector lists the contents of the vector.
I'd like to be able to write my own way for "showing" the contents of a specific type of object. Ideally, I'd like to be able to seperate this from existing types of objects.
How would I go about doing this?
Here's an example to get you started. Once you get the basic idea of how S3 methods are dispatched, have a look at any of the print methods returned by methods("print") to see how you can achieve more interesting print styles.
## Define a print method that will be automatically dispatched when print()
## is called on an object of class "myMatrix"
print.myMatrix <- function(x) {
n <- nrow(x)
for(i in seq_len(n)) {
cat(paste("This is row", i, "\t: " ))
cat(x[i,], "\n")
}
}
## Make a couple of example matrices
m <- mm <- matrix(1:16, ncol=4)
## Create an object of class "myMatrix".
class(m) <- c("myMatrix", class(m))
## When typed at the command-line, the 'print' part of the read-eval-print loop
## will look at the object's class, and say "hey, I've got a method for you!"
m
# This is row 1 : 1 5 9 13
# This is row 2 : 2 6 10 14
# This is row 3 : 3 7 11 15
# This is row 4 : 4 8 12 16
## Alternatively, you can specify the print method yourself.
print.myMatrix(mm)
# This is row 1 : 1 5 9 13
# This is row 2 : 2 6 10 14
# This is row 3 : 3 7 11 15
# This is row 4 : 4 8 12 16
Related
I'm trying to use a new R package called waldo (see at the tidyverse blog too) that is designed to compare data objects to find differences. The waldo::compare() function returns an object that is, according to the documentation:
a character vector with class "waldo_compare"
The main purpose of this function is to be used within the console, leveraging coloring features to highlight outstanding values that are not equal between data objects. However, while just examining in console is useful, I do want to take those values and act on them (filter them out from the data, etc.). Therefore, I want to programmatically extract the outstanding values. I don't know how.
Example
Generate a vector of length 10:
set.seed(2020)
vec_a <- sample(0:20, size = 10)
## [1] 3 15 13 0 16 11 10 12 6 18
Create a duplicate vector, and add additional value (4) into an 11th vector element.
vec_b <- vec_a
vec_b[11] <- 4
vec_b <- as.integer(vec_b)
## [1] 3 15 13 0 16 11 10 12 6 18 4
Use waldo::compare() to test the differences between the two vectors
waldo::compare(vec_a, vec_b)
## `old[8:10]`: 12 6 18
## `new[8:11]`: 12 6 18 4
The beauty is that it's highlighted in the console:
But now, how do I extract the different value?
I can try to assign waldo::compare() to an object:
waldo_diff <- waldo::compare(vec_a, vec_b)
and then what? when I try to do waldo_diff[[1]] I get:
[1] "`old[8:10]`: \033[90m12\033[39m \033[90m6\033[39m \033[90m18\033[39m \n`new[8:11]`: \033[90m12\033[39m \033[90m6\033[39m \033[90m18\033[39m \033[34m4\033[39m"
and for waldo_diff[[2]] it's even worse:
Error in waldo_diff[3] : subscript out of bounds
Any idea how I could programmatically extract the outstanding values that appear in the "new" vector but not in the "old"?
As a disclaimer, I didn't know anything about this package until you posted so this is far from an authoritative answer, but you can't easily extract the different values using the compare() function as it returns an ANSI formatted string ready for pretty printing. Instead the workhorses for vectors seem to be the internal functions ses() and ses_context() which return the indices of the differences between the two objects. The difference seems to be that ses_context() splits the result into a list of non-contiguous differences.
waldo:::ses(vec_a, vec_b)
# A tibble: 1 x 5
x1 x2 t y1 y2
<int> <int> <chr> <int> <int>
1 10 10 a 11 11
The results show that there is an addition in the new vector beginning and ending at position 11.
The following simple function is very limited in scope and assumes that only additions in the new vector are of interest:
new_diff_additions <- function(x, y) {
res <- waldo:::ses(x, y)
res <- res[res$t == "a",] # keep only additions
if (nrow(res) == 0) {
return(NULL)
} else {
Map(function(start, end) {
d <- y[start:end]
`attributes<-`(d, list(start = start, end = end))
},
res[["y1"]], res[["y2"]])
}
}
new_diff_additions(vec_a, vec_b)
[[1]]
[1] 4
attr(,"start")
[1] 11
attr(,"end")
[1] 11
At least for the simple case of comparing two vectors, you’ll be better off
using diffobj::ses_dat() (which is from the package that waldo uses
under the hood) directly:
waldo::compare(1:3, 2:4)
#> `old`: 1 2 3
#> `new`: 2 3 4
diffobj::ses_dat(1:3, 2:4)
#> op val id.a id.b
#> 1 Delete 1 1 NA
#> 2 Match 2 2 NA
#> 3 Match 3 3 NA
#> 4 Insert 4 NA 3
For completeness, to extract additions you could do e.g.:
extract_additions <- function(x, y) {
ses <- diffobj::ses_dat(x, y)
y[ses$id.b[ses$op == "Insert"]]
}
old <- 1:3
new <- 2:4
extract_additions(old, new)
#> [1] 4
How do I assign to a dynamically created vector?
master<-c("bob","ed","frank")
d<-seq(1:10)
for (i in 1:length(master)){
assign(master[i], d )
}
eval(parse(text=master[2]))[2] # I can access the data
# but how can I assign to it THIS RETURNS AN ERROR #######################
eval(parse(text=master[2]))[2]<- 900
OK. I'll post this code but only because I was asked to:
> eval(parse(text=paste0( master[2], "[2]<- 900" ) ) )
> ed
[1] 1 900 3 4 5 6 7 8 9 10
It's generally considered bad practice to use such a method. You need to build the expression" ed[2] < 100. Using paste0 lets you evaluate master[2] as 'ed' which is then concatenated with the rest of the characters before passing to parse for convert to a language object. This would be more in keeping with what is considered better practice:
master<-c("bob","ed","frank")
d<-seq(1:10)
mlist <- setNames( lapply(seq_along(master), function(x) {d} ), master)
So changing the second value of the second item with <-:
> mlist[[2]][2] <- 900
> mlist[['ed']]
[1] 1 900 3 4 5 6 7 8 9 10
I'm trying to create a function that automatically creates polynomials of a zoo object. Coming from Python, the typical way to it is to create a list outside a for loop, and then append the list inside the loop. Following this, I wrote the below code in R:
library("zoo")
example<-zoo(2:8)
polynomial<-function(data, name, poly) {
##creating the catcher object that the polynomials will be attached to
returner<-data
##running the loop
for (i in 2:poly) {
#creating the polynomial
poly<-data^i
##print(paste(name, i), poly) ##done to confirm that paste worked correctly##
##appending the returner object
merge.zoo(returner, assign(paste(name, i), poly))
}
return(returner)
}
#run the function
output<-polynomial(example, "example", 4)
However, when I run the function, R throws no exceptions, but the output object does not have any additional data beyond what I originally created in the example zoo object. I suspect I'm misunderstanding merge.zoo or perhaps now allowed to dynamically reassign the names of the polynomials inside the loop.
Thoughts?
As for error in your code you are missing assignment of result from merge.zoo to returner.
However, I think there is better way to achieve what you want.
example <- zoo(2:8)
polynomial <- function(data, name, poly) {
res <- zoo(sapply(1:poly, function(i) data^i))
names(res) <- paste(name, 1:4)
return(res)
}
polynomial(example, "example", 4)
## example 1 example 2 example 3 example 4
## 1 2 4 8 16
## 2 3 9 27 81
## 3 4 16 64 256
## 4 5 25 125 625
## 5 6 36 216 1296
## 6 7 49 343 2401
## 7 8 64 512 4096
I have a named list of vectors that represent events originated from 2 samples, "A" and "B":
l.temp <- list(
SF1_t_A = c(rep(1:10)),
SF2_t_A = c(rep(9:15)),
SF1_t_B = c(rep(8:12)))
l.temp
$SF1_t_A
[1] 1 2 3 4 5 6 7 8 9 10
$SF2_t_A
[1] 9 10 11 12 13 14 15
$SF1_t_B
[1] 8 9 10 11 12
Now I want select only the elements of the list that are either from sample "A" or "B". I could go about doing it with a loop but that sort of defies the point of using list when plyr is around. This, and variations, is what I've tried so far:
llply(l.temp , function(l){
if ((unlist(strsplit(names(l), "_"))[3]) == "A"){
return(l)}
})
This is the error I am getting:
Error in unlist(strsplit(names(l), "_")) :
error in evaluating the argument 'x' in selecting a method for function 'unlist':
Error in strsplit(names(l), "_") : non-character argument
Help on what I am doing wrong is appreciated.
You can find the pattern in the names of the list, which gives you an index of which ones:
grep("_A$", names(l.temp))
And then use it to subset:
l.temp[grep("_A$", names(l.temp))]
I do:
assign('test', 'bye')
test
[1] "bye"
now, I have the vector inside 'test' variable.
I would like to use the string inside 'test' variable as name of a column of the follow list:
list(test=c(1:10))
$test
[1] 1 2 3 4 5 6 7 8 9 10
But I would like to use 'bye' as NAME (because 'bye' is wrote inside the test variable)
How can I do it?
I don't think eval or assign are at all necessary here; their use usually (although not always) indicates that you're doing something the hard way, or at least the un-R-ish way.
> test <- "bye"
> L <- list(1:10) ## c() unnecessary here too
> names(L) <- test
> L
$bye
[1] 1 2 3 4 5 6 7 8 9 10
If you really want to do this in a single statement, you can do:
L <- setNames(list(1:10), test)
or
L <- structure(list(1:10), .Names=test)
I guess this will be the answer you're looking for?
assign('test','bye')
z<-list(c(1:10))
names(z)<-test