Да, теперь мне нало посохранять все 100500 графиков, которые ваша покорная слуга сгенерировала.
Note that
If a value is specified for
If any input into an element of the result is in UTF-8 (and none are declared with encoding
If an input into an element is declared with encoding
ъ
Отлично! Поняла! По деволту функция paste() ставит пробел между строками, что она соединяет. Чтобы она ставила её, необходимо в качестве сепаратор апоставить просто две кавычки, означающие, что разделителя нет и не будет! Пишется это так:
Ай да я! Ай да молодец! Отлично! Теперь попробую вызвать функцию записи :) Теперь присвоим эту всю фигню в переменную, чтобы удобно было передавать и вызовем ещё раз нашу функцию записи в пдф :)
f <- read.csv("C:/Users/MSI/Desktop/Diploma/raw_data_v71.csv",header = TRUE, sep=";", quote="\"", encoding = "UTF-8");
names(f) <- c("FROM","TO", "MIGR", "TO_POP", "FROM_LAT", "FROM_LON", "TO_LAT","TO_LON" , "DISTANCE", "FR_OKTMO", "TO_OKTMO", "SAME_REG", "ADM2", "ADM1", "M2PRICE");
MigrMore5 <- f[f$MIGR >5, ];
citiesMore5 <- unique(MigrMore5$FROM) ;
citiesMore5 <- as.vector(citiesMore5);
for (i in 1:length(citiesMore5))
{
City <- MigrMore5[MigrMore5$FROM == citiesMore5[i], ];
lnMIGR <- log(City$MIGR);
lnDISTANCE <- log(City$DISTANCE);
lnPOP <- log(City$TO_POP);
LinearModel <- lm(lnMIGR ~ lnDISTANCE + lnPOP);
#препарируем результат
coef<- LinearModel[[1]];
res <- LinearModel[[2]];
dimention<-dim(City);
#len <- dimention[2];
deep <-dimention[1];
prediction <- matrix(0, 1, deep);
for (i in 1:deep) #1:6
{
prediction[i] <- coef[1] + coef[2]*lnDISTANCE[i] + coef[3]*lnPOP[i] + res[i];
}
plot(lnMIGR, prediction, xlab = "Real migration", ylab = "Predicted migration");
prediction1 <- as.vector(prediction);
lm <- lm(prediction1 ~ lnMIGR);
abline(lm);
}
pdf("C:/Users/MSI/Desktop/Diploma/Rplot.pdf", paper = "a4") > plot(lnMIGR, prediction, xlab = "Real migration", ylab = "Predicted migration"); > lm <- lm(prediction1 ~ lnMIGR); > line <- abline(lm); > dev.off() Теперь осталось придумать, как мне автоматически менять названия у графиков. Может, пойти через конкатинацию строк? Почитаем, что ж мне там пишет хелп :)А за конкатинацию отвечает эта функция:Basic string operations
There are three string functions that are closely related to their base R equivalents, but with a few enhancements:
str_c()is equivalent topaste(), but it uses the empty string (“”) as the default separator and silently removesNULLinputs.str_length()is equivalent tonchar(), but it preserves NA’s (rather than giving them length 2) and converts factors to characters (not integers).str_sub()is equivalent tosubstr()but it returns a zero length vector if any of its inputs are zero length, and otherwise expands each argument to match the longest. It also accepts negative positions, which are calculated from the left of the last character. The end position defaults to-1, which corresponds to the last character.str_str<-is equivalent tosubstr<-, but likestr_subit understands negative indices, and replacement strings not do need to be the same length as the string they are replacing.Three functions add new functionality:
str_dup()to duplicate the characters within a string.str_trim()to remove leading and trailing whitespace.str_pad()to pad a string with extra whitespace on the left, right, or both sides.Pattern matching
stringr provides pattern matching functions to detect, locate, extract, match, replace, and split strings. I’ll illustrate how they work with some strings and a regular expression designed to match (US) phone numbers:strings <- c( "apple", "219 733 8965", "329-293-8753", "Work: 579-499-7527; Home: 543.355.3679" ) phone <- "([2-9][0-9]{2})[- .]([0-9]{3})[- .]([0-9]{4})"
str_detect()detects the presence or absence of a pattern and returns a logical vector (similar togrepl()).str_subset()returns the elements of a character vector that match a regular expression (similar togrep()withvalue = TRUE)`.# Which strings contain phone numbers? str_detect(strings, phone) #> [1] FALSE TRUE TRUE TRUE str_subset(strings, phone) #> [1] "219 733 8965" #> [2] "329-293-8753" #> [3] "Work: 579-499-7527; Home: 543.355.3679"str_locate()locates the first position of a pattern and returns a numeric matrix with columns start and end.str_locate_all()locates all matches, returning a list of numeric matrices. Similar toregexpr()andgregexpr().# Where in the string is the phone number located? (loc <- str_locate(strings, phone)) #> start end #> [1,] NA NA #> [2,] 1 12 #> [3,] 1 12 #> [4,] 7 18 str_locate_all(strings, phone) #> [[1]] #> start end #> #> [[2]] #> start end #> [1,] 1 12 #> #> [[3]] #> start end #> [1,] 1 12 #> #> [[4]] #> start end #> [1,] 7 18 #> [2,] 27 38str_extract()extracts text corresponding to the first match, returning a character vector.str_extract_all()extracts all matches and returns a list of character vectors.# What are the phone numbers? str_extract(strings, phone) #> [1] NA "219 733 8965" "329-293-8753" "579-499-7527" str_extract_all(strings, phone) #> [[1]] #> character(0) #> #> [[2]] #> [1] "219 733 8965" #> #> [[3]] #> [1] "329-293-8753" #> #> [[4]] #> [1] "579-499-7527" "543.355.3679" str_extract_all(strings, phone, simplify = TRUE) #> [,1] [,2] #> [1,] "" "" #> [2,] "219 733 8965" "" #> [3,] "329-293-8753" "" #> [4,] "579-499-7527" "543.355.3679"str_match()extracts capture groups formed by()from the first match. It returns a character matrix with one column for the complete match and one column for each group.str_match_all()extracts capture groups from all matches and returns a list of character matrices. Similar toregmatches().# Pull out the three components of the match str_match(strings, phone) #> [,1] [,2] [,3] [,4] #> [1,] NA NA NA NA #> [2,] "219 733 8965" "219" "733" "8965" #> [3,] "329-293-8753" "329" "293" "8753" #> [4,] "579-499-7527" "579" "499" "7527" str_match_all(strings, phone) #> [[1]] #> [,1] [,2] [,3] [,4] #> #> [[2]] #> [,1] [,2] [,3] [,4] #> [1,] "219 733 8965" "219" "733" "8965" #> #> [[3]] #> [,1] [,2] [,3] [,4] #> [1,] "329-293-8753" "329" "293" "8753" #> #> [[4]] #> [,1] [,2] [,3] [,4] #> [1,] "579-499-7527" "579" "499" "7527" #> [2,] "543.355.3679" "543" "355" "3679"str_replace()replaces the first matched pattern and returns a character vector.str_replace_all()replaces all matches. Similar tosub()andgsub().str_replace(strings, phone, "XXX-XXX-XXXX") #> [1] "apple" #> [2] "XXX-XXX-XXXX" #> [3] "XXX-XXX-XXXX" #> [4] "Work: XXX-XXX-XXXX; Home: 543.355.3679" str_replace_all(strings, phone, "XXX-XXX-XXXX") #> [1] "apple" #> [2] "XXX-XXX-XXXX" #> [3] "XXX-XXX-XXXX" #> [4] "Work: XXX-XXX-XXXX; Home: XXX-XXX-XXXX"str_split_fixed()splits the string into a fixed number of pieces based on a pattern and returns a character matrix.str_split()splits a string into a variable number of pieces and returns a list of character vectors.Arguments
Each pattern matching function has the same first two arguments, a character vector ofstrings to process and a singlepattern(regular expression) to match. The replace functions have an additional argument specifying the replacement string, and the split functions have an argument to specify the number of pieces.Unlike base string functions, stringr offers control over matching not through arguments, but through modifier functions,regexp(),coll()andfixed(). This is a deliberate choice made to simplify these functions. For example, whilegreplhas six arguments,str_detect()only has two.Regular expressions
To be able to use these functions effectively, you’ll need a good knowledge of regular expressions, which this vignette is not going to teach you. Some useful tools to get you started:
A good reference sheet. When writing regular expressions, I strongly recommend generating a list of positive (pattern should match) and negative (pattern shouldn’t match) test cases to ensure that you are matching the correct components.Functions that return lists
Many of the functions return a list of vectors or matrices. To work with each element of the list there are two strategies: iterate through a common set of indices, or useMap()to iterate through the vectors simultaneously. The second strategy is illustrated below:col2hex <- function(col) { rgb <- col2rgb(col) rgb(rgb["red", ], rgb["green", ], rgb["blue", ], max = 255) } # Goal replace colour names in a string with their hex equivalent strings <- c("Roses are red, violets are blue", "My favourite colour is green") colours <- str_c("\\b", colors(), "\\b", collapse="|") # This gets us the colours, but we have no way of replacing them str_extract_all(strings, colours) #> [[1]] #> [1] "red" "blue" #> #> [[2]] #> [1] "green" # Instead, let's work with locations locs <- str_locate_all(strings, colours) Map(function(string, loc) { hex <- col2hex(str_sub(string, loc)) str_sub(string, loc) <- hex string }, strings, locs) #> $`Roses are red, violets are blue` #> [1] "Roses are #FF0000, violets are blue" #> [2] "Roses are red, violets are #0000FF" #> #> $`My favourite colour is green` #> [1] "My favourite colour is #00FF00"Another approach is to use the second form ofstr_replace_all(): if you give it a named vector, it applies eachpattern = replacementin turn:matches <- col2hex(colors()) names(matches) <- str_c("\\b", colors(), "\\b") str_replace_all(strings, matches) #> [1] "Roses are #FF0000, violets are #0000FF" #> [2] "My favourite colour is #00FF00"
Usage
paste (..., sep = " ", collapse = NULL) paste0(..., collapse = NULL)
Arguments
... | one or more R objects, to be converted to character vectors. |
sep | a character string to separate the terms. Not NA_character_. |
collapse | an optional character string to separate the results. Not NA_character_. |
Details
paste converts its arguments (via as.character) to character strings, and concatenates them (separating them by the string given bysep). If the arguments are vectors, they are concatenated term-by-term to give a character vector result. Vector arguments are recycled as needed, with zero-length arguments being recycled to "".Note that
paste() coerces NA_character_, the character missing value, to "NA" which may seem undesirable, e.g., when pasting two character vectors, or very desirable, e.g. in paste("the value of p is ", p).paste0(..., collapse) is equivalent to paste(..., sep = "", collapse), slightly more efficiently.If a value is specified for
collapse, the values in the result are then concatenated into a single string, with the elements being separated by the value of collapse.Value
A character vector of the concatenated values. This will be of length zero if all the objects are, unlesscollapse is non-NULL in which case it is a single empty string.If any input into an element of the result is in UTF-8 (and none are declared with encoding
"bytes", (see Encoding), that element will be in UTF-8, otherwise in the current encoding in which case the encoding of the element is declared if the current locale is either Latin-1 or UTF-8, at least one of the corresponding inputs (including separators) had a declared encoding and all inputs were either ASCII or declared.If an input into an element is declared with encoding
"bytes", no translation will be done of any of the elements and the resulting element will have encoding "bytes". If collapse is non-NULL, this applies also to the second, collapsing, phase, but some translation may have been done in pasting object together in the first phase.ъ
Examples
paste(1:12) # same as as.character(1:12)
paste("A", 1:6, sep = "")
stopifnot(identical(paste ("A", 1:6, sep = ""),
paste0("A", 1:6)))
paste("Today is", date())
Отлично! Поняла! По деволту функция paste() ставит пробел между строками, что она соединяет. Чтобы она ставила её, необходимо в качестве сепаратор апоставить просто две кавычки, означающие, что разделителя нет и не будет! Пишется это так:
> paste("C:/Users/MSI/Desktop/Diploma/", as.character(citiesMore5[13]), ".pdf", sep = "") [1] "C:/Users/MSI/Desktop/Diploma/Магадан.pdf"
Ай да я! Ай да молодец! Отлично! Теперь попробую вызвать функцию записи :) Теперь присвоим эту всю фигню в переменную, чтобы удобно было передавать и вызовем ещё раз нашу функцию записи в пдф :)
adress <- paste("C:/Users/MSI/Desktop/Diploma/", as.character(citiesMore5[13]), ".pdf", sep = "");
> pdf(adress, paper = "a4");
> plot(lnMIGR, prediction, xlab = "Real migration", ylab = "Predicted migration");
> lm <- lm(prediction1 ~ lnMIGR);
> line <- abline(lm);
> dev.off();
Записалось!
А теперь попробуем всё тоже самое записать в формате .png. О! Оказывается, и в других форматах тоже можно сохранять!
bmp(filename = "Rplot%03d.bmp",
width = 480, height = 480, units = "px", pointsize = 12,
bg = "white", res = NA, family = "", restoreConsole = TRUE,
type = c("windows", "cairo"), antialias)
jpeg(filename = "Rplot%03d.jpg",
width = 480, height = 480, units = "px", pointsize = 12,
quality = 75,
bg = "white", res = NA, family = "", restoreConsole = TRUE,
type = c("windows", "cairo"), antialias)
png(filename = "Rplot%03d.png",
width = 480, height = 480, units = "px", pointsize = 12,
bg = "white", res = NA, family = "", restoreConsole = TRUE,
type = c("windows", "cairo", "cairo-png"), antialias)
tiff(filename = "Rplot%03d.tif",
width = 480, height = 480, units = "px", pointsize = 12,
compression = c("none", "rle", "lzw", "jpeg", "zip", "lzw+p", "zip+p"),
bg = "white", res = NA, family = "", restoreConsole = TRUE,
type = c("windows", "cairo"), antialias)
Arguments
filenamethe name of the output file, up to 511 characters. The page number is substituted if a C integer format is included in the character string, as in the default, and tilde-expansion is performed (see path.expand). (The result must be less than 600 characters long. See postscript for further details.)
widththe width of the device.
heightthe height of the device.
unitsThe units in which height and width are given. Can be px (pixels, the default), in (inches), cm or mm.
pointsizethe default pointsize of plotted text, interpreted as big points (1/72 inch) at res ppi.
bgthe initial background colour: can be overridden by setting par("bg").
qualitythe ‘quality’ of the JPEG image, as a percentage. Smaller values will give more compression but also more degradation of the image.
compressionthe type of compression to be used.
resThe nominal resolution in ppi which will be recorded in the bitmap file, if a positive integer. Also used for units other than the default. If not specified, taken as 72 ppi to set the size of text and line widths.
familyA length-one character vector specifying the default font family. The default means to use the font numbers on the Windows GDI versions and "sans" on the cairographics versions.
restoreConsoleSee the ‘Details’ section of windows. For type == "windows" only.
typeShould be plotting be done using Windows GDI or cairographics?
antialiasLength-one character vector.
For allowed values and their effect on fonts with type = "windows" see windows: for that type if the argument is missing the default is taken from windows.options()$bitmap.aa.win.
For allowed values and their effect (on fonts and lines, but not fills) with type = "cairo" see svg.
f <- read.csv("C:/Users/MSI/Desktop/Diploma/raw_data_v71.csv",header = TRUE, sep=";", quote="\"", encoding = "UTF-8");
names(f) <- c("FROM","TO", "MIGR", "TO_POP", "FROM_LAT", "FROM_LON", "TO_LAT","TO_LON" , "DISTANCE", "FR_OKTMO", "TO_OKTMO", "SAME_REG", "ADM2", "ADM1", "M2PRICE");
MigrMore5 <- f[f$MIGR >5, ];
citiesMore5 <- unique(MigrMore5$FROM) ;
citiesMore5 <- as.vector(citiesMore5);
for (i in 1:length(citiesMore5))
{
City <- MigrMore5[MigrMore5$FROM == citiesMore5[i], ];
lnMIGR <- log(City$MIGR);
lnDISTANCE <- log(City$DISTANCE);
lnPOP <- log(City$TO_POP);
LinearModel <- lm(lnMIGR ~ lnDISTANCE + lnPOP);
#препарируем результат
coef<- LinearModel[[1]];
res <- LinearModel[[2]];
dimention<-dim(City);
#len <- dimention[2];
deep <-dimention[1];
prediction <- matrix(0, 1, deep);
for (i in 1:deep) #1:6
{
prediction[i] <- coef[1] + coef[2]*lnDISTANCE[i] + coef[3]*lnPOP[i] + res[i];
}
plot(lnMIGR, prediction, xlab = "Real migration", ylab = "Predicted migration");
prediction1 <- as.vector(prediction);
lm <- lm(prediction1 ~ lnMIGR);
abline(lm);
}

Комментариев нет:
Отправить комментарий