# prirazeni hodnoty (value assignment) x <- -7 x = -7 x = 10 x == 0 x != 0 x == 10 x != 10 x>0 x<0 x>=0 x>=10 x<=10 -x>=10 ### Matematicke funkce (mathematic function) # absolutni hodnota (absolute value) abs(x) # nasobeni a deleni (multiplication and division) 3*3 x*3 9/3 x/3 (x-3)/(x/3) 1/0 log(0) Inf*Inf Inf/Inf 0/0 # celociselne deleni (intager division) 13%/%2 library(numbers) div(13,2) # zbytek po deleni (reminder after division) 13%%2 mod(13,2) library(numbers) # Determine whether p is the power of an integer. isIntpower(144) isIntpower(8) library(schoolmath) x <- c(1.002, 2, 3.14, 4, 5, 6.31, 7) schoolmath::is.decimal(x) schoolmath::is.whole(x) library(FRACTION) FRACTION::is.wholenumber(x, tol = .Machine$double.eps^0.5) x <- c(1, 2, 3, 4, 5, 6, 7) schoolmath::is.even(x) schoolmath::is.odd(x) x %% 2 == 0 x %% 2 != 0 is.even <- function(x) x %% 2 == 0; is.even(x) is.odd <- function(x) x %% 2 != 0; is.odd(x) x <- c(-1, -2, 3.02, 4, -5.2, 6, -7) schoolmath::is.negative(x) schoolmath::is.positive(x) schoolmath::is.real.positive(x) x <- c(1, 2, 3, 4, 5, 6, 7) schoolmath::is.prim(x) library(DescTools) DescTools::IsPrime(x) library(numbers) numbers::isPrime(x) library(cmna) cmna::isPrime(x) is.integer(x) library(ttutils) isInteger(x) isInteger(c("test", 1, 2, 2.1)) # vektor (vector) ### Rozklad na prvocísla (decomposition to primes) ### library(schoolmath) schoolmath::prime.factor(21) schoolmath::prime.factor(100) library(DescTools) DescTools::Factorize(47) DescTools::Factorize(seq(101, 111, by=2)) library(numbers) numbers::primeFactors(21) # Find All Primes Less Than n library(DescTools) DescTools::Primes(100) library(schoolmath) schoolmath::primes(start = 12, end = 99) library(numbers) numbers::Primes(99) numbers::Primes(n1 = 12, n2 = 99) library(numbers) # nejblizsi vyssi prvocislo (nearest higher prime) numbers::nextPrime(12) numbers::previousPrime(12) ### Prirozene cislo (intager) library(litteR) is_natural_number(12) is_natural_number(1.2) library(numbers) numbers::isNatural(x) ### Prevod desetinných císel na zlomky (Convert decimal numbers to fractions) ### library(MASS) fractions(-0.1666667) fractions(0.14) fractions(0.4) x = fractions(-0.1666667) frsp = strsplit(as.character(x),"/") as.numeric(frsp[[1]][1]) # citatel (numerator) as.numeric(frsp[[1]][2]) # jmenovatel (denominator) library(fractional) fractional(-0.1666667, eps = 1e-06, maxConv = 20, sync = FALSE) library(FRACTION) fra(-0.1666667) # nefunguje (not function) fra(0.14) fra(0.4) ### zjednodusení zlomku (fractions simplification) ### library(schoolmath) cancel.fraction(42, 56) cancel.fraction(-167, 100) fra(-0.1666667) cancel.fraction(-1666667, 1e+07) # nefunguje decimal2fraction(0.1,6) # funguje library(fractional) fractional(-0.1666667, eps = 1e-06, maxConv = 20, sync = FALSE) numerators(-0.1666667) # vypise citatele (numerator) denominators(-0.1666667) # vypise jmenovatele (denominator) numerical(fractional(-0.1666667, eps = 1e-06, maxConv = 20, sync = FALSE)) unfractional(fractional(-0.1666667, eps = 1e-06, maxConv = 20, sync = FALSE)) ### Nejvetsí spolecný delitel (greatest common divisor) ### x = 12 y = 8 library(schoolmath) schoolmath::gcd(x, y) library(FRACTION) FRACTION::gcd(x, y) library(DescTools) DescTools::GCD(x, y, na.rm = FALSE) DescTools::GCD(c(10,12,8), na.rm = FALSE) library(numbers) numbers::GCD(12, 10) numbers::GCD(46368, 75025) numbers::mGCD(c(2, 3, 5, 7) * 11) numbers::mGCD(c(2*3, 3*5, 5*7)) numbers::coprime(12, 10) # maji/nemaji prvociselneho delitele numbers::coprime(46368, 75025) ### Nejmensí spolecný násobek (smallest common multiple) ### x = 12 y = 8 library(schoolmath) schoolmath::scm(x, y) library(DescTools) DescTools::LCM(x, y) DescTools::LCM(c(12,10,8), na.rm = FALSE) library(numbers) numbers::LCM(12, 10) numbers::LCM(46368, 75025) numbers::mLCM(c(2, 3, 5, 7) * 11) numbers::mLCM(c(2*3, 3*5, 5*7)) # odmocnina (root) sqrt(x) x^(1/2) x^(-1/2) # mocnina (power) x**2 x^2 x^(-2) # goniometricke a hyperbolicke funkce (geometric and hyperbolic function) cos(x) sin(x) tan(x) acos(x) asin(x) atan(x) atan2(y, x) cospi(x) # cos(pi*x) sinpi(x) # sin(pi*x) tanpi(x) # tan(pi*x) cosh(x) sinh(x) tanh(x) acosh(x) asinh(x) atanh(x) # logaritmy (logarithm) x = 10 log(x) # base e log(x, base = exp(1)) # base e logb(x, base = exp(1)) # base e log10(x) # base 10 log(x,base = 10) log2(x) # base 2 log(x,base = 2) log1p(x) # computes log(1+x) # exponenty (exponents) 10^x # exponent 10**x # exponent exp(x) # e^x ### vektory (vectores) ######################################################################## 1:6 c(2:12) rev(c(2:12)) seq(from=1, to=20, by=2) seq(5, -5, -1) seq(from=5, by=-1, along.with = 1:20) rep(1, len = 9) rep(1:4, len = 9) rep(1:4, 2) rep(1:4, each = 2) # not the same. rep(1:4, c(2,2,2,2)) # same as second. rep(1:4, c(2,1,2,1)) rep(1:4, each = 2, len = 4) # first 4 only. rep(1:4, each = 2, len = 10) # 8 integers plus two recycled 1's. rep(1:4, each = 2, times = 3) # prazdny vektor () xx = NULL is.null(xx) is.null(x) # nahodna cisla sample(12:99, 9, replace = FALSE) # bez opakovani sort(sample(1:20, 9, replace = FALSE)) sample(12:99, 9, replace = TRUE) # s opakovanim sort(sample(1:20, 9, replace = TRUE)) # rada prvocísel library(DescTools) DescTools::Primes(100) library(schoolmath) schoolmath::primes(start = 12, end = 99) library(numbers) numbers::Primes(99) numbers::Primes(n1 = 12, n2 = 99) # rada Fibonacciho cisel (z daného rozmezi) library(numbers) fibonacci(50, sequence = TRUE) # rada náhodných císel z daného rozmezí # set.seed(123) runif(n=5, min=0, max=1) # rovnomerne rozdeleni runif(6,-2,2) sample(12:99, 9, replace = FALSE) # bez opakovani sort(sample(1:20, 9, replace = FALSE)) sample(12:99, 9, replace = TRUE) # s opakovanim sort(sample(1:20, 9, replace = TRUE)) library(gdata) resample(1:20, 9, replace = FALSE, prob = NULL) resample(1:20, 9, replace = TRUE, prob = NULL) # normalni rozdeleni rnorm(n=6, mean=0, sd=1) rnorm(6,9,1.5) rbinom(30,c(0,1),0.5) #mince rbinom(30,c(1:6),(1/6)) #kostka (dice) # indexy set.seed(123) x = sample(12:99,19, replace = FALSE) is.vector(x) x x[1] x[1:5] x[c(1:5)] x[length(x)] x[(length(x)-1)] x[-1] x[-(1:5)] x[-c(1:5)] x[-length(x)] x[length(x)-3:length(x)]#poslednich 6 hodnot x[c(1,4,7)]#vybrane hodnoty which.max(x) which.min(x) library(Rmpfr) which.min(x) which(x<=50) x[which(x<=50)] x[x<=50] which(x>=50) x[which(x>=50)] which(x == max(x))#maximalni hodnota which(x == 10) which(x != 10) x[x > 40]#hodnoty vyssi nez 400. x[x < 40]#hodnoty mensi nez 100 which(x > 10)#hodnoty vyssi nez 10. which(x < 10)#hodnoty mensi nez 10. seq_along(x) rank(x) # vhodne pro vektory, nevhodne pro matice is.unsorted(x) sort(x) sort(x, decreasing = FALSE) sort(x, decreasing = TRUE) sort(x[which(x>=50)]) order(x) # poradi (indexy) pro sort x[order(x)] # Vector Arithmetics a = c(1, 3, 5, 7) b = c(1, 2, 4, 8) 5 * a a + b a - b a * b a / b u = c(10, 20, 30) v = c(1, 2, 3, 4, 5, 6, 7, 8, 9) u + v max(x) min(x) range(x) library(DescTools) Range(x) sum(x) cumsum(x) prod(x) cumprod(x) diff(x) sign(x) x = sample(12:99, 9, replace = TRUE) x unique(x) table(x) summary(as.factor(x)) # frekvence vyskytu daneho cisla sum(x==57) length(which(x==57)) numbers =c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,7,65,34,435) table(numbers)[2]==1 numbers[2] sum(numbers==435) duplicated(numbers) # identifying duplicated elements numbers[duplicated(numbers)] unique(numbers) # extracting unique elements, ifelse(x<50,0,1) x[x<50] = 0 x[x>=50] = 1 x set.seed(123) x = sample(12:99,19) x ### matice ################################################################### x1 = sample(12:99,19, replace = FALSE) x2 = sample(12:99,19, replace = TRUE) x12 = rbind(x1,x2) x12 = cbind(x1,x2) is.matrix(x12) nrow(x12) ncol(x12) x12[order(x1),] x12[order(x2),] x12[,1] x12[,"x"] colnames(x12) colnames(x12)=c("X","Y") rownames(x12) rownames(x12) = LETTERS[1:length(x1)] ### dataframes ################################################################################## x1 = sample(12:99,19, replace = FALSE) x2 = sample(12:99,19, replace = TRUE) z = LETTERS[1:length(x1)] x12 = rbind(x1,x2,z) x12 = cbind(x1,x2,z) nrow(x12) ncol(x12) is.data.frame(x12) is.matrix(x12) as.data.frame(x12) is.data.frame(x12) colnames() rownames() ### lists ########################################################################################### x1 = sample(12:99,19, replace = FALSE) x2 = sample(12:99,19, replace = TRUE) x3 = sample(12:99,19, replace = TRUE) x123 = list(x1,x2,x3) is.list(x123) names(x123) = c("x1","x2","x3") unlist(x123) do.call(rbind,x123) do.call(cbind,x123) stack(x123) ############################################################################################################## ############################################################################################################## #### Fyzikalni konstanty ########################################################################################################## ### Ludolfovo cislo #### pi print(pi, digits=20) ### Eulerovo cislo #### exp(1) print(exp(1), digits=20) library(marelac) data(Constants) Constants Constants$gasCt1 Constants$gasCt2 Constants$gasCt3 R = as.numeric(Constants$gasCt2[1]); R # hodnota Constants$gasCt2[2] # jednotka ### Vylepseni mm = "gas" consts = do.call(rbind,Constants) # list to dataframe MM = sapply(consts[,3], function(xxx) grepl(mm, xxx, fixed = TRUE)) SMM = consts[which(MM==TRUE),] SMM # zadat poradi polozky ve vystupu SMM[2,] # pro 1 polozku SMM[1] R = as.numeric(SMM[2,1]); R # hodnota SMM[2,2] # jednotka library(constants) codata lookup("planck", ignore.case=TRUE) lookup("avogadro", ignore.case=TRUE) lookup("faraday", ignore.case=TRUE) lookup("molar", ignore.case=TRUE) lookup("molar mass", ignore.case=TRUE) lookup("light", ignore.case=TRUE) lookup("boltzmann", ignore.case=TRUE) lookup("mass", ignore.case=TRUE) lookup("mass constant", ignore.case=TRUE) lookup("proton mass", ignore.case=TRUE) lookup("electron mass", ignore.case=TRUE) # Univerzalni plynova konstanta lookup("gas", ignore.case=TRUE) codata[214,] R = as.numeric(codata[214,3]) # hodnota Ru = as.numeric(codata[214,5]) # nejistota codata[214,4] # jednotka #### Atomove a molekulove hmotnosti ################################################################################################################################### library(periodicTable) data(periodicTable) periodicTable library(CHNOSZ) # atomova hmotnost AW = mass("Ca"); AW # molarni hmotnost MW = mass("CaCO3"); MW # pocet atomu prvku ve vzorci ce = count.elements("CaCO3"); ce as.chemical.formula(ce, drop.zero = TRUE) library(NORRRM)# archiv # atomova hmotnost data(AtomWeight) AtomWeight AW = AtomWeight["Si","AWeight"]; AW el = c("Ca","Si","Al") AW = AtomWeight[el,'AWeight']; AW names(AW) = el AW # prepocet na oxidy data(OxiWeight) OxiWeight OxiWeight ['Si','OWeight'] library(IsoSpecR) data(isotopicData) isotopicData #### Prevody jednotek ########################################################################################################## library(scales) # % percent(0.05) library(pracma) # uhly vs radiany deg2rad(120) rad2deg(3.14) library(measurements) conv_unit_options # pouzivane jednotky # length conv_unit(1, from="mm", to="m") conv_unit(1, from="nm", to="angstrom") # pressure conv_unit(101, from="Pa", to="mmHg") conv_unit(1, from="atm", to="Pa") # temperature conv_unit(100, from="C", to="K") # energy conv_unit(500, from="cal", to="J") conv_unit(1, from="erg", to="J") #volume conv_unit(100, from="l", to="m3") # mass conv_unit(100, from="g", to="mg") conv_unit(100, from="ug", to="g") # speed conv_unit(1, from="km_per_hr", to="m_per_sec") conv_unit(1, from="light", to="km_per_hr") conv_unit(1, from="light", to="m_per_sec") ### multiunits conv_multiunit(x = 1, from="ug / l", to="g / m3") conv_multiunit(x = 1, from="mg / l", to="kg / m3") conv_multiunit(x = 1, from="cal / kg", to="J / g") ### Plynný systém mení svuj objem o 1200 ml za konstantního vnejsího tlaku 30 atm.Jakou práci vykoná plyn pri expanzi? Vyjádrete v ruzných energetických jednotkách. # W = p . dV dV = 1200 # [ml] dV = conv_unit(dV, from="ml", to="m3"); dV p = 30 # [atm] to [Pa] p = conv_unit(p, from="atm", to="Pa"); p W = p*dV; W # [J] W1 = conv_unit(W, from="J", to="cal"); W1 # [cal] W2 = conv_unit(W, from="J", to="Wsec"); W2 # [W.s] W3 = conv_unit(W, from="J", to="erg"); W3 # [erg] ### Kolik tepla se uvolní pri pruchodu 26.43 coulombu elektrického proudu vodicem pri potenciálovém spádu 2.432 V. # 64.33 J, 64.33e7 erg, 15.37 cal # Q = U . I . t = U . q q = 26.43 # [C] U = 2.432 # [V] Q = U*q; Q # [J] Q1 = conv_unit(Q, from="J", to="cal"); Q1 # [cal] Q3 = conv_unit(Q, from="J", to="erg"); Q3 # [erg] # Prevod casovych jednotek library(datetime) xx = as.minute(7658) # 7658 min as.second(xx) as.hour(xx) as.day(xx) ### Pokus trval 7658 minut. Kolik je to dní, hodin a minut? tt = 7658 # [min] library(lubridate) seconds_to_period(tt*60) library(datetime) seconds_to_period(as.second(as.minute(tt))) # opacny vypocet library(datetime) dur <- duration(week = 0, day = 5, hours = 7, minutes = 38) as.numeric(dur, "minutes") #### nasobky jednotek SI library(sitools) f2si(10000) f2si(0.023, unit="l") f2si(3.5e-5, unit="mol") numbers <- c(1e5, 3.5e-12, 0.004) f2si(numbers, unit="g") ############################################################################################################## #### Nacitani externich dat ########################################################################################################## pisky<- read.table("c:\\Users\\lubop\\Documents\\kurs\\DVpisky1.txt", header=T) pisky<- read.csv("c:\\Users\\lubop\\Documents\\kurs\\DVpisky1.csv", header=T) library(openxlsx) shn = getSheetNames("c:\\Users\\lubop\\Documents\\kurs\\DVpisky1.xlsx") shn pisky <- read.xlsx("c:\\Users\\lubop\\Documents\\kurs\\DVpisky1.xlsx", sheet = "DVPisky", startRow = 1, colNames = TRUE, rowNames = TRUE,detectDates = FALSE, skipEmptyRows = TRUE,rows = NULL, cols = NULL,check.names = FALSE) summary(pisky) pisky = pisky[,-1] #### NA and data imputation ##################################################################################################### ### vektory x = pisky[,"Sr"] length(x) x[4] = NA any(is.na(x)) is.na(x) library(jwutil) # rel. podil hodnot ve vektoru propIsNa(x) xx = na.omit(x) length(xx) ### Matice a dataframes x = pisky x[5,5]<- NA any(is.na(x)) is.na(x) library(ryouready) count_na(x, along = 1) count_na(x, along = 2) # along: 1 = rows, 2=columns library(jwutil) # rel. podil hodnot ve sloupcich propNaPerField(x) library(agricolae) delete.na(x, alternative="less") delete.na(x, alternative="greater") # "less" = vynechava sloupce # "greater" = vynechava radky ### Imputace library(DescTools) ZeroIfNA(x) NAIfZero(x) # BlankIfNA(x, blank="") BlankIfNA(x, blank="UDL") NAIfBlank(x) library(jwutil) # NA na 0 zero_na(x) zero_na(x, na_ish = TRUE) library(DescTools) # nahrazeni medianem sloupce x5 = Impute(x[,5], FUN = function(x) median(x, na.rm = TRUE)) rbind(x[,5],x5,pisky[,5]) x[,5] = x5 # nahrazeni library(compositions) # nahrazeni nasobkem DL x0 = ZeroIfNA(x) # library(DescTools) dl=rep(0.1,ncol(x)) # vektor DL xdl = zeroreplace(x0[,5],d = 0.1,a = 1/2) x[,5] = xdl # nahrazeni library(na.tools) all_na(x) any_na(x) is_na(x) which_na(x[,5]) which_na(x[5,]) xdl = na.replace(x[,5], .na=0.05) x[,5] = xdl # nahrazeni na.constant(x[,5], 0.05) na.max(x[,5]) na.min(x[,5]) na.mean(x[,5]) na.median(x[,5]) na.quantile(x[,5], prob=0.4 ) na.mode(x[,5]) na.most_freq(x[,5]) na.inf(x[,5]) na.neginf(x[,5]) na.true(x[,5]) na.false(x[,5]) na.zero(x[,5]) set.seed(123) xb = na.bootstrap(x[,5]) xr = na.resample(x[,5]) rbind(x[,5],xb,xr,pisky[,5]) ### ZAOKROUHLOVANI ########################################################################################## # Zaokrouhlovani na dany pocet desetinnych mist ##### round(1234.567,2) round(123.456,digits=2) library(guf) round_something(123.456, decimals = 2) round_something("123.456", decimals = 2) library(PKNCA) roundString(3141.59265, digits = 3, sci_range = 0, sci_sep = "e") roundString(3141.59265, digits = 3, sci_range = 0, sci_sep = "x10^") roundString(3141.59265, digits = 3, sci_range = Inf, sci_sep = "e") # Pocet desetinnych mist daneho cisla decimalplaces <- function(x) { # error due to rounding double precision floating point numbers -- replacing the x %% 1 if (abs(x - round(x)) > .Machine$double.eps^0.5) { nchar(strsplit(sub('0+$', '', as.character(x)), ".", fixed = TRUE)[[1]][[2]]) } else { return(0) } } decimalplaces(3.14) decimalplaces(3.1415) decimalplaces(3.14159265) #### Zaokrouhlovani na dany pocet platnych cislic ######### signif(1234.567,4) signif(123.456,digits=4) library(PKNCA) signifString(3141.59265, digits = 1, sci_range = 0, sci_sep = "e") signifString(3141.59265, digits = 1, sci_range = 0,sci_sep = "x10^") signifString(3141.59265, digits = 1, sci_range = Inf, sci_sep = "e") # Urceni poctu platnych cislic daneho cisla sigdig <- function(x) length(gregexpr("[[:digit:]]", as.character(x))[[1]]) sigdig(3.14) sigdig(3.1415) sigdig(3.14159265) ### Relativni chyba zaokrouhleneho cisla X = 0.053450 n = 2 # zvoleny pocet platnych cislic library(PKNCA) # nacist funkci sigdig() A = as.numeric(substring(signifString(X, digits = sigdig(X), sci_range = 0, sci_sep = "e"), 1, 1)) s = 1/(2*A*10^(n-1)); s library(scales) percent(s) library(jwutil) percentize(s)