# 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 ########################################################################################################## path = "c:\\Users\\lubop\\Documents\\kurs\\" file.names <- dir(path, pattern =".txt");file.names pisky<- read.table("c:\\Users\\lubop\\Documents\\kurs\\DVpisky1.txt", header=T) xx = "Kyjov2.txt" pisky<- read.table(paste("c:\\Users\\lubop\\Documents\\kurs\\",xx,sep=""), 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[,"vek"] length(x) #x[4] = NA any(is.na(x)) is.na(x) which(is.na(x)=="TRUE") library(jwutil) # rel. podil hodnot ve vektoru propIsNa(x) apply(pisky,2,propIsNa) 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") ############################################################################################################################################### ### if - else ### ### Vypocítejte vazebnou energii atomového jádra pomoci Bethe - Weiszackerovy rovnice # B = 14.0 - 13.1*A^(2/3) + 0.585*Z*(Z-1)/A^(1/3) - (18.1*(A-2*Z)^2)/A + C/A # A - nukleonove cislo, Z - atomove cislo, C - konstanta, pro jadra se sudym poctem protonu a neutronu je rovna 132, # pro jadra s lichym poctem protonu a neutronu je rovna -132, pro lichy pocet protonu a sudy pocet neutronu a naopak je rovna 0. # alpha particle A = 4 Z = 2 # U-235 A = 235 Z = 92 N = A-Z if (N%%2==0 & Z%%2==0){C = 132} else if (N%%2!=0 & Z%%2!=0){C = -132} else {C = 0} B = 14.0 - 13.1*A^(2/3) + 0.585*Z*(Z-1)/A^(1/3) - (18.1*(A-2*Z)^2)/A + C/A B # [MeV] B/A # energie na 1 nukleon [MeV] # polomer jadra: R = R0 * A^(1/3) R0 = 1.4e-13 # [cm] R = R0 * A^(1/3) R = R*10e-15 R # [m] ### Anorganická kvalitativní analýza - 1. skupina KAA1 <- function(){ print("Kvalitativni analyza - 1. skupina iontu (Ag, Pb, Hg)") print("Odpovidejte a (ano) nebo n (ne)") print("Pozor. Nez zacnete, prepnete se do konzole.") an <- readline(prompt="Chcete pokracovat? " ) if (an == "n") {print("Tak snad nekdy jindy ...") } else {print("Takze zaciname ...") an <- readline(prompt="Vznikla po pridani HCl bila srazenina? " ) if (an == "n") {print("Neni pritomen zadny prvek 1. skupiny.") } else {print("Je pritomno olovo, stribro, rtut, nebo jejich kombinace.") an <- readline(prompt="Rozpousti se srazenina zcela v horke vode? " ) if (an == "a") {print("Je pritomno pouze olovo.") } else { an <- readline(prompt="Rozpousti se srazenina alespon castecne? " ) if (an == "a") {print("Je pritomno olovo, ale take stribro a/nebo rtut.") } else {print("Olovo neni pritomno, jsou pritomny stribro a/nebo rtut.")} an <- readline(prompt="Rozpousti se srazenina zcela v amoniaku? " ) if (an == "a") {print("Je pritomno stribro, neni pritomna rtut.") } else { an <- readline(prompt="Rozpousti se srazenina alespon castecne? " ) if (an == "a") {print("Je pritomno stribro, a take rtut.") } else {print("Neni pritomno stribro, je pritomna rtut.")} an <- readline(prompt="Doslo pridavkem amoniaku ke zcernani srazeniny? " ) if (an == "a") {print("Rtut je potvrzena.") } else {print("To je divne. Nekde se stala chyba ...")} } } } print("Hotovo. Nashledanou priste.") } } KAA1() ### while cyklus (while loop) ### ### Vypocitejte molekulove hmotnosti alkanu C1 - C12 n = 1 Mhc = NULL while(n <= 12){ hc = n*12.011 + (2*n + 2)*1.008 Mhc = c(Mhc,hc) n = n+1 } names(Mhc) = c(1:12) Mhc ### switch switch(2,"red","green","blue") switch(1,"red","green","blue") # Jednoducha kalkulacka pro scitani, odcitani, nasobeni a deleni simcalc = function(){ add <- function(x, y) { return(x + y)} subtract <- function(x, y) { return(x - y) } multiply <- function(x, y) { return(x * y) } divide <- function(x, y) { return(x / y)} # take input from the user num1 = as.integer(readline(prompt="Enter first number: ")) choice = as.character(readline(prompt="Enter choice[+, -, *, /]: ")) num2 = as.integer(readline(prompt="Enter second number: ")) result <- switch(choice, "+"=add(num1, num2), "-"=subtract(num1, num2), "*"=multiply(num1, num2), "/"=divide(num1, num2)) print(paste(num1, choice, num2, "=", result)) } simcalc() # s do.call() # grafy s moznosti vyberu kombinace promennych # https://www.datamentor.io/r-programming/switch-function/ # https://www.datamentor.io/r-programming/examples/simple-calculator/ # https://stackoverflow.com/questions/10393508/how-to-use-the-switch-statement-in-r-functions # https://stackoverflow.com/questions/31156957/use-of-switch-in-r-to-replace-vector-values # ### iterace, rovnice, integraly - presnost ### for cyklus (for loop) ### ### Vypocitejte molekulove hmotnosti alkanu C1 - C12 Mhc = NULL for(n in c(1:12)){ hc = n*12.011 + (2*n + 2)*1.008 Mhc = c(Mhc,hc) } names(Mhc) = c(1:12) Mhc ### Vypocitejte stredni kvadratickou rychlost molekul danych plynu v rozmezi teplot od 150 K do 500 K s krokem 50 K. el = c("H2","He", "O2", "Kr") M = c(2.0159, 4.0026, 31.9988, 83.8) # [g / mol] Ts = seq(from=150, to=500, by=50) # [K] R = 8314.34 # [J / kmol K] MKV = NULL for(tt in Ts){ mkv= rep(0, length(M)) for(ii in c(1:length(M))){ mkv[ii] = (3*R*tt/M[ii])^(1/2) } MKV = rbind(MKV, mkv) } colnames(MKV) = el rownames(MKV) = Ts MKV plot(0,0,xlim=c(min(Ts),max(Ts)),ylim = c(min(MKV),max(MKV)), type ="n",xlab="T [K]",ylab="str. kv. rychlost [m/s]") for(ii in c(1:length(M))){points(Ts,MKV[,ii], type="p",col=ii,pch=16)} legend("topleft",legend=el,col=c(1:length(M)),pch=16,cex=.8) ### apply funkce ### # https://www.r-bloggers.com/r-tutorial-on-the-apply-family-of-functions/ # http://www.datasciencemadesimple.com/apply-function-r/ ### lapply a sapply (vektory, seznamy) ### ### Vypocitejte molekulove hmotnosti alkanu C1 - C12. # lapply Mhc = lapply(c(1:12), function(n){n*12.011 + (2*n + 2)*1.008}) Mhc = unlist(Mhc) names(Mhc) = c(1:12) Mhc # sapply Mhc = sapply(c(1:12), function(n){n*12.011 + (2*n + 2)*1.008}) names(Mhc) = c(1:12) Mhc ### tapply (matice, dataframes) ### ### Effectiveness of Insect Sprays: The counts of insects in agricultural experimental units treated with different insecticides. data(InsectSprays) InsectSprays tapply(InsectSprays$count,InsectSprays$spray,mean) tapply(InsectSprays$count,InsectSprays$spray,sd) tapply(InsectSprays$count,InsectSprays$spray,length) tapply(InsectSprays$count,InsectSprays$spray,boxplot.stats) # by (x, INDICES, FUN, ...) by(as.data.frame(mtcars), list(cyl,vs), FUN=mean) # aggregate(x, by, FUN, …, simplify = TRUE, drop = TRUE) # aggregate(formula, data, FUN, …, subset, na.action = na.omit) attach(mtcars) aggdata <-aggregate(mtcars, by=list(cyl,vs), FUN=mean, na.rm=TRUE) print(aggdata) # https://www.r-bloggers.com/aggregate-a-powerful-tool-for-data-frame-in-r/ # https://stackoverflow.com/questions/9809166/count-number-of-rows-within-each-group # https://www.r-bloggers.com/how-to-aggregate-data-in-r/ # https://stats.stackexchange.com/questions/8225/how-to-summarize-data-by-group-in-r # https://datascienceplus.com/aggregate-data-frame-r/ # # mean pomoci sapply a lapply (pres indexy) xx = as.character(unique(InsectSprays$spray)) insp = sapply(xx, function(x){mean(InsectSprays$count[which(InsectSprays$spray==x)])}) insp insp = lapply(xx, function(x){mean(InsectSprays$count[which(InsectSprays$spray==x)])}) names(insp) = xx insp = unlist(insp) insp # mean pomoci sapply a lapply (pres seznamy) xx = split(InsectSprays$count, InsectSprays$spray, drop = FALSE) names(xx) = as.character(unique(InsectSprays$spray)) insp = lapply(names(xx),function(x){mean(xx[[x]])}) names(insp) = names(xx) unlist(insp) insp = sapply(names(xx),function(x){mean(xx[[x]])}) insp ### apply a pbapply (matice, dataframes) ### n<-1000 mat<-matrix(rnorm(n),ncol=10,nrow=100) # apply() x<-apply(mat,1,sum) x<-apply(mat,2,sum) # pbapply() library(pbapply) # pridava progress bar v konzoli x<-pbapply(mat,1,sum) x<-pbapply(mat,2,sum) # https://www.r-bloggers.com/pbapply/ # https://www.r-bloggers.com/how-to-add-pbapply-to-r-packages-2/ # library(purrr) library(doBy) library(AggregateR) ### Red wine characteristics and quality: dataset related to wine samples from north Portugal. library(live) data(wine) wine apply(wine, 2, mean) apply(wine, 2, sd) apply(wine, 2, length) apply(wine, 2, boxplot.stats) library(pbapply) pbapply(wine, 2, mean) pbapply(wine, 2, sd) pbapply(wine, 2, length) pbapply(wine, 2, boxplot.stats) # mean pomoci sapply a lapply wn = sapply(c(1:length(wine[1,])), function(x){mean(wine[,x])}) names(wn) = colnames(wine) wn # wn = lapply(c(1:length(wine[1,])), function(x){mean(wine[,x])}) names(wn) = colnames(wine) wn